I want to write a small language by TypeScript and I define the basic data type for it:
type BasicDataType = {
kind: 'text'
} | {
kind: 'number'
};
Then I defined a generic type to express its instance:
type BasicInstance<B extends BasicDataType> = B extends { kind: 'number' } ?
number
: B extends { kind: 'text' } ?
string
: never;
let a: BasicInstance<{ kind: 'number' }> = 1;
let b: BasicInstance<{ kind: 'text' }> = '';
It works well, but when I try to define a advanced type and its instance:
type DataType = {
kind: 'single',
t: BasicDataType
} | {
kind: 'array',
t: BasicDataType,
};
type Instance<D extends DataType> = D extends { kind: 'single', t: infer B } ?
BasicInstance<B>
: D extends { kind: 'array', t: infer B } ?
Array<BasicInstance<B>>
: never;
I got the error:
error TS2344: Type 'B' does not satisfy the constraint 'BasicDataType'. Type 'B' is not assignable to type '{ kind: "number"; }'.
It seems TypeScript cannot understand that B must be a BasicDataType. Why it happen? And How do I fix it?
{ kind: 'text' }or{ kind: 'number' }. The only thing it could be derive is B = BasicDataType.