如何向此介面添加簽名,以便打字稿理解當前值可能用作某個物件的索參考于索引型別
export interface StateInterface {
list: {
current: string; // itmesA or itmesB
itmesA: string[];
itmesB: string[];
};
const state =
list: {
current: 'itemesA'
itmesA: ['1','2','3'];
itmesB: ['4','5','6'];
};
let showItems = context.list[context.list.current][0]}
uj5u.com熱心網友回復:
string可以是任何東西,但只能使用特定的字串來索引該物件。這意味著您可以使鍵更具體,以便該current屬性只能是正確的鍵之一。
export interface StateInterface {
list: {
current: 'itmesA' | 'itmesB';
itmesA: string[];
itmesB: string[];
};
}
操場
或者更巧妙的是,您不必兩次鍵入鍵名:
export interface StateInterface {
list: {
current: keyof StateInterface['list']; // though this makes `current` a valid key
itmesA: string[];
itmesB: string[];
};
}
操場
或者也許使用其他型別使事情更清潔。
interface SomeLists {
itmesA: string[];
itmesB: string[];
}
export interface StateInterface {
list: SomeLists & {
current: keyof SomeLists;
};
}
操場
有很多方法可以解決這個問題。選擇哪個是基于如何使用這種型別的意見。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/371415.html
上一篇:反應組件道具拋出錯誤打字稿
