Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

Typescript - narrow type based on object dictionary?

See the code below, I'm selecting one of two functions to run from dictionary based on the type property in the input object.

However, because the result is a union function, Typescript throws an error.

Does anybody know how to work around this?

type typeA = {
  type: A
}

type typeB = {
  type: B
}

const dictionary = 
{
  A: function fA (input: typeA)...
  B: function fB (input: typeB)...
}

const input : typeA | typeB = XYZ;

const pickedFunc = dictionary[input.type]; // input.type === 'A' | 'B' (literal union)

pickedFunc(input) // <--- Error! "typeA | typeB" is not compatible with function of "typeof fA | typeof fB"



与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is not possible as types are not evaluated at runtime. The typescript code has by that point become javascript without any static type checking. You could however use a type guard, you can read about this here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...