[英]TypeScript: populate JSON object with each key type in string based on the interface
[英]Typescript: get type of interface property based on interface key
我正在構建一個 function 需要一次更新 object 的一個字段。 這個 object 是通過接口T
定義的。
interface T {
a: TypeA;
b: TypeB;
c: TypeC;
}
這應該是這個 function 的類型簽名:
(key: keyof T, value: typeof T[key]) => void
這會產生錯誤: 'key' refers to a value, but it is being used as a type here. Did you mean 'typeof key'?
'key' refers to a value, but it is being used as a type here. Did you mean 'typeof key'?
. IMO我不是說typeof key
,因為typeof key
可以是T
的任何鍵,但是如果key = a
等,我希望value
屬性為TypeA
類型。
我怎樣才能 select T
的對應鍵值的類型?
您正在嘗試使用實際值索引類型,這是不允許的。 您需要使用類型( playground )訪問它:
interface T {
a: number;
b: string;
c: boolean;
}
const func = <K extends keyof T>(key: K, value: T[K]) => {};
func("a", 5);
func("b", 5); // Argument of type 'number' is not assignable to parameter of type 'string'.
typescript 中的類型和實際值之間有明顯的區別,因為類型信息在轉譯后丟失。 因此,您不能使用實際值來定義類型邏輯。 唯一的方法是提取真實值的類型值(例如,使用typeof
),這就是編譯器建議將真實值轉換為類型的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.