![](/img/trans.png)
[英]Typescript constrain generic to string literal type for use in computed object property
[英]Constrain generic's object property type
假設我們有一些參數是字符串的函數
const action = (param: string) => {
return param;
};
還有一個通用類型
interface Relation<T, K extends keyof T> {
store: T;
storeKey: K;
}
以及接受Relation
類型參數並執行action
函數
const testFunction = <T, K extends keyof T>({ store, storeKey }: Relation<T, K>) => {
action(store[storeKey]);
};
現在 TypeScript 錯誤消息是store[storeKey] is not assignable to type string
,我明白為什么。 如果T[K]
不是字符串(沒有類型保護,只有靜態類型檢查),有沒有辦法“棄用” testFunction
調用?
UPD:T 不僅可以具有字符串屬性
您應該指定更具體的類型而不是T
即T extends Record<string, string>
:
const action = (param: string) => {
return param;
};
interface Relation<T extends Record<string, string>, K extends keyof T> {
store: T;
storeKey: K;
}
const testFunction = <T extends Record<string, string>, K extends keyof T>({ store, storeKey }: Relation<T, K>) => {
action(store[storeKey]);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.