1

How can I infer the type of T in TypeScript 2.9.2 here:

type Class<T extends object> = new(...args: any[]) => T
type Conditional<T> = T extends number ? Class<Number> : T extends string ? Class<String> : never
function<T>(conditional: Conditional<T>) {}
f(Number) // I want to infer T here from given Number

I want to infer T = number but instead I get an error saying NumberConstructor is assignable to never!

Does TypeScript automatic type inference works here?

Thank you!

1 Answer 1

3

I don't think inference from conditional types is implemented in TypeScript. It's not really possible to implement in the general case anyway (how clever do you have to be to determine a function's input given its output? probably more clever than a compiler). In any case you probably don't need it. What if you did something like this:

type Class<T extends object> = new (...args: any[]) => T
type Unconditional<T extends Class<Number> | Class<String>> = 
  T extends Class<Number> ? number : T extends Class<String> ? string : never
function f<CT extends Class<Number> | Class<String>, T=Unconditional<CT>>(
  conditional: CT
) {}

f(Number) // infers as CT=NumberConstructor, T=number

In this case you are using the Unconditional conditional type to produce T from CT... that is, instead of trying to infer the input from the output, you just calculate the output from the input.

You didn't specify where you need T... so I can't tell whether it's best to have the function be f<CT, T>, or instead just f<CT> and tell you to use Unconditional<CT> wherever you were planning to use T.

Anyway, hope that gives you some ideas. Good luck.

Sign up to request clarification or add additional context in comments.

1 Comment

Is this still true in current versions? Seems like T is not inferred as unknown in similar cases in Typescript 4.5.4. Playground Link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.