Laurence Dougal Myers
Laurence Dougal Myers

Reputation: 1072

TypeScript - string literal type is not assignable to type parameter extending string literal type

I have some code like this:

type FooType = 'Bar';

abstract class Meow<T extends FooType> {
  baz: T = 'Bar';
}

This gives the error Type '"Bar"' is not assignable to type 'T'..

I don't understand this error. If baz has type T, shouldn't it allow any value from FooType?

How can I make the class property baz accept any value conforming toFooType, in addition to other string literals that sub-classes might want?

Upvotes: 0

Views: 486

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249606

A generic type constraint specifies the minimal contract the type parameters needs to satisfy, but T could be a type that has more required properties than your constraint specifies. This is why typescript generally does not allow asignment of literals to anything with a generic type.

Consider the following code:

type FooType = 'Bar';

class Meow<T extends FooType> {
  baz: T = 'Bar';
}

let m = new Meow<'Bar' & { extra: number }>()
m.baz.extra // why is extra not assigned as it's type suggests it should be ?

For string literal types I agree the example above might seem a bit contrived, but it's possible under the type system. I believe there was a suggestion to allow this to work anyway, but I a not sure if it will be implemented.

To get around this check, the simplest solution it to use a type assertion:

class Meow<T extends FooType> {
  baz: T = 'Bar' as T;
}

Upvotes: 1

Related Questions