type和interface的区别

type的用法实例

type test = number; //基本类型
let num: test = 10;
type userOjb = {name:string} // 对象
type getName = ()=>string  // 函数
type data = [number,string] // 元组
type numOrFun = Second | getName  // 联合类型
type User = {
    name: string
    age: number
};
type SetUser = (name: string, age: number)=>void;

interface可以扩展,type可以通过交叉实现interface的extends行为
interface可以extends type,同时type也可以与interface类型交叉

interface Name {
  name: string;
}
interface User extends Name {
  age: number
}
let stu:User = {name: 'wang', age: 10}
//interface的扩展可以通过type交叉(&)类型实现
type Name = {
   name: string;
}
type User = Name & {age: number}
let stu:User={name: 'wang', age: 18}
//interface 扩展 type
type Name = {
  name: string;
}
interface User extends Name {
  age: number;
}
let stu:User={name: 'wang', age: 89}
//type与interface交叉
interface Name {
  name: string;
}
type User = Name & {
  age: number;
}
let stu:User={name:'wang', age: 18}

type 能使用 in 关键字生成映射类型,但interface不行

type Keys = "name" | "sex"
type DuKey = {
  [Key in Keys]: string //类似 for ... in
}
let stu: Dukey = {
  name: 'wang',
  sex: 'man'
}

你可能感兴趣的:(前端)