Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Typescript type can not be inferred if function parameter is used

Lets say i have this generic function:

const myFn = <T>(p: {
  a: (n: number) => T,
  b: (o: T) => void,
}) => {
  // ...
}

If i use myFn with no parameter for function a it works and the type of T can be inferred from the return type of a:

myFn({
  a: () => ({ n: 0 }), // Parameter of a is ignored
  b: o => { o.n }, // Works!
})

but if i want to use the parameter for function a suddenly the type of T can not be inferred:

myFn({
  a: i => ({ n: 0 }), // Parameter i is used
  b: o => { o.n }, // Error at o: Object is of type 'unknown'.ts(2571)
})

Can someone explain this behavior? How can i fix this such that the type of T can be inferred from the return type of a?

question from:https://stackoverflow.com/questions/65540887/typescript-type-can-not-be-inferred-if-function-parameter-is-used

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

1 Reply

0 votes
by (71.8m points)

Extra generic for b should help:

const myFn = <T,>(p: {
  a: (n: number) => T,
  b: <U extends T /* EXTRA U generic */>(o: U) => void,
}) => {
  // ...
}


myFn({
  a: () => ({ n: 0 }), // Parameter of a is ignored
  b: o => { o.n }, // Works!
})

myFn({
  a: i => ({ n: 0 }), // Parameter i is used
  b: o => { o.n }, // Works 
})

This article should help to understand why your approach did not work


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...