我在Typescript 中使用Generics时遇到了一些问题.
我想使用Generics基于另一个对象类型创建一个对象. 我的起点是this doc from TS
这就是我到目前为止所想到的:
type ClickableItem<T extends Record<string, any>, K extends keyof T> = {
label: string;
key: K;
render?: (value: T[K]) => string;
// The value (argument) type here should reflect the type from the selected key
};
当前的结果
如果我try 在对象中使用此LinkableProject类型,我将获得所有可能类型值的render
个联合的参数类型,例如:
type Example = {
a: string,
b: number
}
const item = {
label: 'x',
key: 'a',
render: (value) => value //ERROR HERE
} satisfies ClickableItem<Example, keyof Example>
即使键a
被专门设置为类型string
,渲染方法也被错误地推断为类型string | number
在之前的示例中,方法渲染的类型应该是(value: string)=> string
,而不是推断的类型(value: number | string)=> string
.
这里有the ts playground link个,包括TS Doc中的原始示例和我之前提到的测试实现