0

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?

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.