You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
typePerson={name: string,age: number}// Inferred!// return type is { name: string, age: number }functioncreatePerson(){return{name: "Stefan",age: 39}}// Inferred!// me is type of { name: string, age: number}constme=createPerson()// Annotated! You have to check if types are compatiblefunctionprintPerson(person: Person){console.log(person.name,person.age)}// All worksprintPerson(me)
要注意到的是 return type 不同, 使用這樣的方式有好處是方便可以製作多型
type : Object.keys的陷阱
typePerson={name: string,age: number,id: number,}declareconstme: Person;Object.keys(me).forEach(key=>{// 💥 the next line throws red squigglies at usconsole.log(me[key])})
https://fettblog.eu/how-not-to-learn-typescript/
多利用 infer 推斷
基本上, 只有 function parameter 一定要加type
要注意到的是 return type 不同, 使用這樣的方式有好處是方便可以製作多型
type : Object.keys的陷阱
解法在這裡:https://fettblog.eu/typescript-better-object-keys/
object.keys 回傳 type為 string[],
但是 TS 認為應該要回傳的type 應該是 'name', 'age', 'id' 而不是所有string
TypeScript 裡面應該避免使用的部分
https://www.executeprogram.com/blog/typescript-features-to-avoid
The text was updated successfully, but these errors were encountered: