olefrank
olefrank

Reputation: 6810

Value as a type in interface

Why is this allowed in Typescript?

interface a {
  age: 42
}

42 is not a type. I thought interfaces should never have implementation details but "real" types like age: number. I see this as a shortcut to an enum age: AgeEnum but not a very pretty one.

Also it confuses the compiler if I do it (confuses 42 with a number). If I do:

class Person implements a { 
  public age: number = 42
}

error: Type number is not assignable to type 42

...which I think is kind of confusing!

I didn't find examples of this in the docs either. Not direct examples anyway.

Can anyone explain to my why this is allowed in Typescript?

Upvotes: 1

Views: 51

Answers (2)

Explosion Pills
Explosion Pills

Reputation: 191729

TypeScript allows for literal types for strings and numbers. In your case, 42 actually is a type: the number 42. This is different than type number.

Note that when you assign numbers and strings to class properties implementing an interface, TypeScript assumes that these are the primitive type rather than the literal type. This may either be a bug or a limitation of TypeScript. You can get around this by specifying the type during assignment.

interface a {
  age: 42;
  name: 'Andrew';
}

class Person implements a {
  age: 42 = 42;
  name: 'Andrew' = 'Andrew';
}

This is more useful when using union types like 42 | 43 | 44.

Upvotes: 0

Igor
Igor

Reputation: 62213

The interface a states that age is limited to the value 42. In your implementation you are redefining the type constraint of field a to number, hence the error.

It is allowed in typescript because you can constrain to primitive literal values. This is actually a really good thing. What if you wanted to change age to ageInDecades and you assume that people would not live past 100 years in age. You could then define the interface constraint on age as follows:

interface IAge {
  ageInDecades: 0|10|20|30|40|50|60|70|80|90|100;
}

This is a rather weak example but I think you get the idea. You can do the same with allowed string values.

Upvotes: 2

Related Questions