One challenge I'm facing is limiting string fields to specific values during compile time, while also allowing these values to be extendable. Let's explore a simplified example:
type Foobar = 'FOO' | 'BAR';
interface SomeInterface<T extends Foobar> {
amember: T;
[key: string]: string; // must remain in place
}
// testing it out
const yes = {
amember: 'FOO'
} as SomeInterface<'FOO'>; // compiles successfully
// const no = {
// amember: 'BAZ'
// } as SomeInterface<'BAZ'>; // Expected error: Type '"BAZ"' does not satisfy the constraint 'Foobar'
// all good so far
// Now here comes the issue
abstract class SomeClass<T extends Foobar> {
private anotherMember: SomeInterface<T>;
}
type Foobarbaz = Foobar | 'BAZ';
class FinalClass extends SomeClass<Foobarbaz> { // Oops, this doesn't work anymore
}
The generated error message states:
Type 'Foobarbaz' does not satisfy the constraint 'Foobar'. Type '"BAZ"' is not assignable to type 'Foobar'.
So my question is: How can I restrict a 'type' in TypeScript to only certain strings, yet allow for extension with additional strings? Or is there a better solution that I might be missing?
Currently using Typescript 2.3.4 but willing to upgrade to 2.4 if it offers any solutions.