我知道如何在變數中宣告型別。
let members: string[] = [] // this works perfectly
我想在一個物件中有一個字串陣列。如何正確格式化?
const team = {
name: String,
members<string[]>: [], // this gives error!!
}
解決方案
const team = {
name: String,
members: [] as string[]
}
uj5u.com熱心網友回復:
一種方法是指定整個物件的型別,就像您正在做的那樣members- 將物件的型別放在冒號之后,=賦值之前:
const team: {
name: StringConstructor;
members: string[];
} = {
name: String,
members: [],
};
另一種方法是僅斷言相關屬性的型別as(但我不喜歡這種方法,因為我更喜歡只使用as來向 TypeScript 指示無法以其他方式注釋的東西)。
const team = {
name: String,
members: [] as string[],
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/414478.html
標籤:
