S
S
sunny_puppy2017-11-20 17:31:45
Angular
sunny_puppy, 2017-11-20 17:31:45

Why does typescript swear at non-interface properties?

export class HeroesComponent implements OnInit {
  hero: Hero = {
    id: 1,
    name: 'Windstorm',
    extra: 'any'
  };

export default interface Hero {
  id: number;
  name: string;
}

The typescript manual makes it clear that the main thing is that the value being assigned should have all the properties specified in the interface (type), but the resulting error * says that the extra property cannot be there. What's the matter, maybe these are some more strict settings?
* TS2322: Type '{ id: number; name:string; extra:string; }' is not assignable to type 'Hero'. Object literal may only specify known properties, and 'extra' does not exist in type 'Hero'.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mikhail Osher, 2017-11-20
@sunny_puppy

export default interface Hero {
  id: number;
  name: string;
  extra?: string;
}

As far as I remember, there is also this notation:
https://www.typescriptlang.org/docs/handbook/advan...
// EDIT
Misunderstood the question. It seems they forgot to update the documentation/examples...
I have long considered this behavior to be default, and I also hang a bunch of strict TS + TSLint rules on top.
https://www.typescriptlang.org/docs/handbook/relea...
TypeScript 1.6 enforces stricter object literal assignment checks for the purpose of catching excess or misspelled properties. Specifically, when a fresh object literal is assigned to a variable or passed as an argument for a non-empty target type, it is an error for the object literal to specify properties that don't exist in the target type.
Actually, if you don’t like this (then why do ts at all??) - try the solutions that I suggested.
// EDIT 2
The behavior you want is called duck typing. For example, it is embedded in the "oop" golang model.
As far as I know, classical strongly typed languages ​​do not allow this. And I agree with them.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question