简体   繁体   中英

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"


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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM