在 TypeScript 中,interface 更偏于一种约束类型,而 type 的作用就是给类型起一个新名字,也就是别名。后来随着TypeScript 语言的发展,type 被赋予了新的内涵,type 也可以用来定义类型。慢慢地人们就开始对这两者的用法产生了疑惑,而本文详细给大家介绍一下 interfacetype 的区别,希望对大家有所帮助。

1、TypeScript interface 和 type 的介绍

在 TypeScript 中,interface 更偏于一种约束类型,同时 TypeScript 也提供了 type 用于定义类型。最初,type 的作用就是给类型起一个新名字,也就是别名,后来随着TypeScript语言的发展,type 被赋予了新的内涵,type 也可以用来定义类型。约束类型与定义类型,本质都是围绕“类型”而产生,所以说interfacetype 在 TypeScript 中区别不大,但是在细微之处,两者的差别也非常明显,需要开发者仔细的体会。本文主要带领大家领略这种细微差别。

在其他面向对象编码语言中,例如 Java 语言中,interface用于定义行为,如果一个类实现了某一个interface则表示该类具有某种行为或者说具有某种能力,例如run或者fly,从而可以通过行为来对动物进行划分,看看它到底是走兽还是飞禽。

type的作用就是给类型起一个新名字,也就是别名,可以作用于原始值(基本类型),联合类型,元组以及其它任何类型。如下代码所示:

type Second = number; // 将number类型命名为Second,从而望文生义,可以推测出其取值范围为0秒到60秒之间
let time: Second = 60;  // time的类型其实就是number类型
type user = {name:string} // 定义user类型
type getName = ()=>string  // 定义函数类型
type data = [number,string] // 定义元组类型
type numOrFun = Second | getName  // 定义联合类型

注意:起别名不会新建一个类型,它创建了一个新名字来引用那个类型。给基本类型起别名通常没什么用。类型别名常用于联合类型。另外,和接口一样,type用来描述对象或函数的类型,如下所示:

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

在ts编译成js后,所有的接口和type都会被擦除掉。

2、TypeScript interface 和 type 的区别

2.1、接口可以扩展,但 type 不能 extends 和 implement 。

接口可以扩展,但type不能extendsimplement。不过,type可以通过交叉类型实现interfaceextends行为。interface 可以extends type,同时type也可以与interface类型交叉。

2.1.1、接口扩展

interface Name {
    name: string;
}
interface User extends Name {
    age: number;
}
let student:User={name:'wang',age:10}

2.1.2、type 交叉

上面的扩展可以用type交叉类型来实现

type Name = {
    name: string;
}
type User = Name & { age: number  };
let student:User={name:'张三',age:20}
console.log(stu)

2.1.3、interface 扩展 type

type Name = {
    name: string;
}
interface User extends Name {
    age: number;
}
let student:User={name:'张三',age:20}

2.1.4、type 与 interface 交叉

interface Name {
    name: string;
}
type User = Name & {
    age: number;
}
let student:User={name:'张三',age:20}

2.2、接口可以定义多次,type不可以定义多次。

接口可以定义多次,并将被视为单个接口(即所有声明属性的合并)。而type不可以定义多次。

interface User {
    name: string
    age: number
}

interface User {
    sex: string
}
let user:User={name:'张三',age:20,sex:'man'}

原文链接:http://www.mybatis.cn/typescript/1992.html

标签: none

[网站公告]-[2024年兼职介绍]


添加新评论