簡體   English   中英

約束泛型的對象屬性類型

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM