#Typescript does not seem to restrict the parameters passed in a constructor

12 messages · Page 1 of 1 (latest)

humble musk
unkempt heath
#

@humble musk What would be the point of interfaces if every property of the class had to appear on the interface?

#

The point of implementing an interface - though there's actually fairly little reason to do so - is to say "the class must have at least these properties.

#

Anything that has a format() method that can be called without arguments and returns a string is a valid HasFormmater. (It doesn't even have to be a class, or use implements HasFormatter - unlike Java)

humble musk
#

@unkempt heath see the above codesnippet

thick summit
#

that is only a requirement in the context of literals

median inletBOT
#
interface Foo {
  foo: string;
}
// error because we are constructing a literal value on the RHS
const foo1: Foo = { foo: "", bar: 1 };
//                           ^^^^^^
// Type '{ foo: string; bar: number; }' is not assignable to type 'Foo'.
//   Object literal may only specify known properties, and 'bar' does not exist in type 'Foo'.

// implictly has the type { foo: "", bar: 1 }
const foo2 = { foo: "", bar: 1 };

// no error, `foo2` is assignable to `Foo`
const foo3: Foo = foo2; 
thick summit
#

an interface merely says what things have in common, not strict what they must be

#

in other languages you might have issues here, but a major different is typescript is a structurally typed language