我剛開始做一些有角度的打字稿,遇到了一個我希望得到幫助的問題。
list = [];
interface a {
s : string;
n : number;
}
const b = {'asdf',1234} as a;
list.push(b)
但我一直收到錯誤
Argument of type a is not assignable to parameter of type 'never'.
關于我能做什么的任何建議?
uj5u.com熱心網友回復:
您必須指定屬性名稱,如下所示:
const b = { s: 'asdf', n: 1234 } as a;
示例打字稿游樂場
uj5u.com熱心網友回復:
當您在類中定義一個陣列成員時,例如:
list = [];
默認情況下,將為 List 分配 type never[],您需要為陣列分配適當的型別,例如:
list: a[] = [];
要么
list: any[] = []; // If you don't care (not as good)
可能您正在 Angular 中定義您的組件,例如:
interface a {
s : string;
n : number;
}
class MyComponentFails {
list = [];
addToList() {
const b = { s: 'asdf', n: 1234} as a;
this.list.push(b) // Argument of type 'a' is not assignable to parameter of type 'never'.
}
}
這不起作用,而是像這樣定義它:
class MyComponentWorks {
list: a[] = [];
addToList() {
const b = { s: 'asdf', n: 1234} as a;
this.list.push(b) // Ok
}
}
操場
uj5u.com熱心網友回復:
您忘記添加鍵名。介面和物件不依賴于引數的位置:
const list = [];
interface A {
s: string;
n: number;
}
const b: A = {s: 'asdf', n: 1234};
list.push(b)
我const為串列宣告添加了缺失。請記住,以大寫字母開頭的型別命名是一種很好的做法。通過這種方式,您可以更輕松地區分變數和型別/介面。還有一種A在 const 附近宣告型別的替代語法b。
uj5u.com熱心網友回復:
查看Object Initializer了解初始化物件的方法。
另請注意,{ 'asdf',1234 } 這也不是有效的物件初始化語法。在許多方式中,有一種用于以這種方式指定物件的簡寫符號(ES2015 起),但是簡寫符號要求這些是有效的變數識別符號,并且物件的鍵和變數的名稱應該相同.
相反,我們可以寫...
const list = [];
interface A {
s: string;
n: number;
}
const s = 'asdf';
const n = 1234;
const b: A = { n, s }; //<-- Short-hand property initializer
list.push(b)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/445943.html
上一篇:通過元組型別引數映射的正確方法
下一篇:元組與硬編碼字串
