【发布时间】:2022-01-11 04:03:42
【问题描述】:
我已经做到了这一点:这似乎有效
function test<types extends Record<string,any>>(dict: dictionary<types>){}
type dictionary<types extends Record<string, any>> = {
[key in keyof types]: {
bar?: types[key];
foo?: (value:types[key])=>true;
};
};
test({
key1:{
bar: 2,
foo: (input:number)=>true,
},
key2:{
bar: 'hello'
foo: (input: number)=>true, // Error! "input" needs to be string
}
})
但是!
我还需要对dict 参数的泛型类型引用。而且由于某种原因,这不起作用
function test2<
types extends Record<string,any>,
dictionary extends dictionary2<types> // <-- Added a generic type
>(dict: dictionary){}
// Same as above
type dictionary2<types extends Record<string, any>> = {
[key in keyof types]: {
bar?: types[key];
foo?: (value:types[key])=>true;
};
};
// Same as above
test2({
key1:{
bar: 2,
foo: (input: number)=>true,
},
key2:{
bar: 'hello',
foo: (input:number)=>true,// Should be an Error (but isn't)! "input" needs to be string
}
【问题讨论】:
-
构建器示例-> here)
标签: javascript typescript typescript-typings typescript-generics