我有一個帶泛型的介面:
我有一個帶泛型的介面。
interface InterfaceWithGenerics<
Dict extends Record<string, any> 。
Key extends keyof Dict = keyof Dictkey: Key;
dictValueFormatter: ((key: Key, value: Dict[Key]) => any);
}
當我定義物件時,它實作了這個介面,我希望泛型被應用于物件屬性并實體化其型別。例如:
interface SomeDictionary {
foo: string;
bar: 數字。
baz: boolean;
}
export const dictConfig: InterfaceWithGenerics<SomeDictionary>[] = [
{
key: 'foo',
dictValueFormatter: (key, value) => `${key}:${value}`。
}
];
但是它沒有發生。VS代碼顯示,在帶有prop key='foo' (Fact)的物件內的dictValueFormatter的輸入如下:
(key: keyof SomeDictionary, value: string | number | boolean) => any
預期:
(key: 'foo', value: string) => any
問題:如何用泛型宣告一個介面,在特定情況下更具體地實體化屬性型別?
uj5u.com熱心網友回復:
你需要定義判別的聯合:
type InterfaceWithGenerics<
Dict extends Record<string, any> 。
>= {
[Key in keyof Dict] 。{
key: Key;
dictValueFormatter: ((key: Key, value: Dict[Key]) => any);
}
}
型別 Values<T> = T[keyof T] 。
介面 SomeDictionary {
foo: string;
bar: 數字。
baz: boolean;
}
export const dictConfig: Values<InterfaceWithGenerics<SomeDictionary>>[] = [
{
key: 'foo'。
dictValueFormatter: (key, value) => `${key}:${value}`。
}
];
請看我的文章
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/318629.html
標籤:
