[英]Typescript error 'argument of type is not assignable to parameter of type'
[英]Argument of type is not assignable error in Typescript
我正在學習打字稿(2.5.2)。 有人可以解釋為什么第一個通話可以,但是第二個通話卻出錯:
function printPerson(person: {firstName: string; lastName: string}): void{
console.log(person.firstName + " " + person.lastName);
}
let geo = {firstName: "geo", lastName: "porz", sex: "M"};
printPerson(geo); //OK here
// TS2345 Argument of type ... is not assignable to parameter of type ...
printPerson({firstName: "geo", lastName: "porz", sex: "M"});
這不是您問題的直接答案,但是我認為您的問題之所以出現是因為您在Typescript中使用了Javascript編碼風格。 來自Javascript,您可能習慣於使用{foo:"bar"}
來傳遞數據。 在Typescript中,如果使用type
或interface
聲明變量的類型,則確實有助於提高代碼的可讀性。
interface Person {
firstName: string
lastName: string
}
function printPerson(person: Person): void{
console.log(person.firstName + " " + person.lastName);
}
現在,當創建一個人員對象時,我們不再依賴類型推斷,而是告訴編譯器geo
是一個人員:
let geo:Person = {firstName: "geo", lastName: "porz", sex: "M"};
現在,您將得到相同的錯誤:您無法將sex
屬性添加到Person,因為未聲明它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.