type和interface的区别

2022-03-17  本文已影响0人  前端小白的摸爬滚打

相同点

interface Example {
  name: string;
  age: number;
}
interface ExampleFunc {
  (name: string, age: number): void;
}

type Example = {
  name: string;
  age: number;
};
type Example = (name: string, age: number) => void;

type 是通过 & (交叉类型)实现,而 interface 是通过 extends 实现

type Type1 = {
  name: string;
};
interface Interface1 {
  name: string;
}

type Type2 = Type1 & {
  age: number;
};
type Type2 = Interface1 & {
  age: number;
};
interface Interface2 extends Type1 {
  age: number;
}
interface Interface2 extends Interface1 {
  age: number;
}

区别

type can but interface can't

interface can but type can't

interface Test {
  name: string;
}
interface Test {
  age: number;
}

/*
        Test实际为 {
            name: string
            age: number
        }
    */
上一篇下一篇

猜你喜欢

热点阅读