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

ts重要知识点 #23

Open
keep-run opened this issue Apr 16, 2020 · 0 comments
Open

ts重要知识点 #23

keep-run opened this issue Apr 16, 2020 · 0 comments

Comments

@keep-run
Copy link
Owner

keep-run commented Apr 16, 2020

索引类型( keyof & T[K ])

使用索引类型,编译器可以检查使用动态属性名的代码。

  • 索引类型查询操作符:keyof。对任何类型Tkeyof T为已知类型T的属性名的联合,比如
interface Person {
    name: string;
    age: number;
}
let personProps:keyof Person    //personProps:"name" | "age"
  • 索引访问操作符:T[K]
interface Person {
  name: string;
  age: number;
}
function demo<T extends object, K extends keyof T>(obj: T, names: K[]): T[K][] {
  return names.map(item => obj[item])
}
let people: Person = {
  name: "test",
  age: 21
}
let res1 = demo(people, ["name"])  //string[] 类型
let res2 = demo(people, ["name",'age'])   //(string|number)[] 类型

T[K] 表明people['name']的类型为Person['name']。

接口(interface) 和 类型别名(type)的区别

类型别名和接口用法相似,但是还是有细微区别

  • 接口创建了新的名字,鼠标放上去,展示的就是接口名,别名没有创建新名称,鼠标悬停展示的是字面量。
  • 类型别名不能被 extends和 implements;

类型区分&类型保护

用户自定义的类型保护

interface Bird {
    fly();
    layEggs();
}

interface Fish {
    swim();
    layEggs();
}
// 有一个变量是Bird或者Fish中的一个,如何区分?
function isFish(pet:Fish|Bird):pet is Fish{
    return (<Fish>pet).swim!==undefined
}

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

No branches or pull requests

1 participant