这是我天真的尝试将泛型类型从参数对象类型MyObject<P>
转换为回调函数。
interface PropsType {
value: number;
}
class MyObject<P extends PropsType> {
readonly props: P;
constructor(props: P) {
this.props = props;
}
}
function doSomething<P extends PropsType, T extends MyObject<P>>(
object: T,
callback: (props: P) => number
): number {
return callback(object.props);
}
const myProps = {
value: 21,
otherValue: 42
}
const myObject = new MyObject(myProps);
// In the callback, props is of type PropsType
doSomething(myObject, (props) => props.otherValue);
// [ts] Property 'otherValue' does not exist on type 'PropsType'.
myObject
正如预期的那样,的类型是MyObject<{ value: number, otherValue: number }>
,所以我期望泛型类型会传播到doSomething
。P
将是{ value: number, otherValue: number }
,然后props
也将是那种类型。
但是,错误清楚地表明props
是 类型PropTypes
,这是 P 可能的最小类型。
有没有办法告诉 Typescript 编译器将完整的P
定义传递给回调,而不是像这样显式地强制类型?
doSomething<
(typeof myObject)['props'],
typeof myObject
>(myObject, (props) => props.otherValue);