我已經走了這么遠:這似乎有效
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
}
游樂場鏈接
uj5u.com熱心網友回復:
你可以這樣做:
function test2<T extends Record<string, unknown>>(dict: Dictionary<T>) { }
type Dictionary<T> = {
[key in keyof T]: {
bar?: T[key];
foo?: (value: T[key]) => true;
};
}
// Same as above
test2({
key1: {
bar: 2,
foo: (input: number) => true,
},
key2: {
bar: 'hello',
foo: (input: number) => true, // Actual error
}
});
打字稿游樂場
uj5u.com熱心網友回復:
更改推理范圍,以便根據該推理而不是第二個型別引數進行types推斷和dict型別化,即,
function test2<
types extends Record<string,any>
>(dict: dictionary2<types>){}
在這里作業的操場。
編輯:使用常規大寫的示例用法
function test2<
T,
>(dict: Dictionary<T>){
type FullDictionary = Dictionary<T> // can't you just use this in your function?
}
type Dictionary<T extends Record<string, any>> = {
[K in keyof T]: DictionaryEntry<T[K]>
}
type DictionaryEntry<T> = {
bar?: T
foo?: (value:T)=>true
}
test2({
key1:{
bar: 2,
foo: (input: number)=>true,
},
key2:{
bar: 'hello',
foo: (input:number)=>true
}
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/373326.html
標籤:javascript 打字稿 打字稿打字 打字稿泛型
