我有陣列:
const studyTypes = [
{
value: "ENG",
label: "ENG-RU",
},
{
value: "RU",
label: "RU-ENG",
},
];
和狀態:
const [typeStudy, setTypeStudy] = React.useState<string>("ENG");
如何在打字稿中指定我typeStudy只能value從studyTypes陣列中獲取一個而不是一個<string>?在這種情況下,typeStudy可以是“ENG”或“RU”。
uj5u.com熱心網友回復:
如果你可以將 studyTypes 宣告為一個常量,它應該是這樣的:
const studyTypes = [
{
value: "ENG",
label: "ENG-RU",
},
{
value: "RU",
label: "RU-ENG",
},
] as const; // as const is important for this step
type Value = typeof studyTypes[number]['value'];
const testValue: Value = "PQR" // This will throw a type error.
這僅適用于 Typescript v3.4 或更高版本。
這是我的 VSCode 檢查 lint 錯誤的示例:

uj5u.com熱心網友回復:
您可以將新型別定義為文字型別。
type TypeStudy = "ENG" | "RU";
進而
React.useState<TypeStudy>
uj5u.com熱心網友回復:
如果僅限于這兩個選項,則執行此操作的一種簡單方法是在型別中準確指定。
const [typeStudy, setTypeStudy] = React.useState<'ENG'|'RU'>("ENG");
您還可以使用映射從物件中提取值并將其設定為型別。
type studyValues = typeof studyTypes.map(study => study.value)
const [typeStudy, setTypeStudy] = React.useState<studyValues>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/370074.html
標籤:javascript 反应 打字稿
