Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TypeScript Handbook - 補充 #354

Open
chochinlu opened this issue Jan 18, 2022 · 0 comments
Open

TypeScript Handbook - 補充 #354

chochinlu opened this issue Jan 18, 2022 · 0 comments

Comments

@chochinlu
Copy link
Owner

chochinlu commented Jan 18, 2022

https://fettblog.eu/how-not-to-learn-typescript/

多利用 infer 推斷

基本上, 只有 function parameter 一定要加type

type Person = {
  name: string,
  age: number
}

// Inferred!
// return type is { name: string, age: number }
function createPerson() { 
  return { name: "Stefan", age: 39}
}

// Inferred!
// me is type of { name: string, age: number}
const me = createPerson() 

// Annotated! You have to check if types are compatible
function printPerson(person: Person) {
  console.log(person.name, person.age)
}

// All works
printPerson(me) 

要注意到的是 return type 不同, 使用這樣的方式有好處是方便可以製作多型

type : Object.keys的陷阱

type Person = {
  name: string, age: number, id: number,
}
declare const me: Person;

Object.keys(me).forEach(key => {
  // 💥 the next line throws red squigglies at us
  console.log(me[key])
})

解法在這裡: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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant