0

What's wrong with this ?
Shouldn't be a string ?

const valueGetter = <T extends {value:V}, V>(o:T) => ():V => o.value 
const myValueGetter = valueGetter({x:1, value:'a string'})  // const myValueGetter: () => {}
const be = myValueGetter() // const be: {}

try it live

1
  • What makes you think it's an object? console.log(typeof be); Commented Jun 21, 2018 at 20:56

1 Answer 1

1

I don't know why, but somehow TypeScript does not recognize the dependency between V and the type of value in T.

In such cases, it helps to be explicit that the desired type comes from a type of a member in T:

const valueGetter = <T extends {value: V}, V>(o: T) => ((): T['value'] => o.value) 
const myValueGetter = valueGetter({x:1, value:'a string'})  // const myValueGetter: () => string
const be = myValueGetter() // const be: string
Sign up to request clarification or add additional context in comments.

3 Comments

You don't really need the type parameter V anymore, you can just use T extends {value: any}.
Nice how-to make it work, and @TitianCernicova-Dragomir you're right! despite this doesn't explain how that bizarre inference occurred...
@aleclofabbro not that bizarre, Typescript doesn't really do dependant generic type parameters, it tries to get away with the least restrictive type posibile when presented with casses such as yours. Conditional types and type queries are the way to work around this.

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.