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
820 views
in Technique[技术] by (71.8m points)

typescript - Simple function with conditional type

The following function was largely lifted from the typescript handbook section on using conditional types, yet it doesn't work:

function test<T extends boolean>(a: T): T extends true ? string : number {
  return a ? '1' : 1
}

Typescript is reporting that:

Type '1 | "1"' is not assignable to type 'T extends true ? string : number'.
  Type '1' is not assignable to type 'T extends true ? string : number'.

I imagine I'm missing something obvious. How can I construct this function so that typescript correctly infers the type based on the function's argument?

I realize that this specific problem could be solved using function signature overloading, but I'd like to learn more about conditional types.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

The short a answer is you can't. No value will be assignable to an unresolved conditional type (a conditional type that still depends on a free generic type variable). The only thing you can do is use a type assertion.

function test<T extends boolean>(a: T): T extends true ? string : number {
  return (a ? '1' : 1)  as any
}

Conditional types are useful to express relations between parameters but they don't help when it comes to implementing the function. Another approach would be to use a more permissive implementation signature.

function test<T extends boolean>(a: T): T extends true ? string : number
function test(a: boolean): number | string {
    return (a ? '1' : 1)
}

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

...