在TypeScript中,类型系统是为了增强JavaScript的类型安全。interface和type都是创建自定义类型的手段,但它们各自有着独特的应用场景和特点。 1️⃣ Interface(接口) 📋 定义 interface用于描述对象的形状(shape),即一组必须遵循的属性和方法的集合。它可以用于类的实现、函数参数的类型约束
比如再定义一个Food接口,Tomato也可以继承Food: interface Vegetables { color: string; } interface Food { type: string; } interface Tomato extends Food, Vegetables { radius: number; } const tomato: Tomato={ type:"vegetables", color:"red", radius:1}; 如果想要覆盖掉继承的属性,那就只能使用兼容的...
❗️interface和type都可以拓展,并且两者并不是相互独立的,也就是说 interface 可以 extends type, type 也可以 extends interface 。 虽然效果差不多,但是两者语法不同。 不同点 1、type 可以声明基本类型别名,联合类型,元组等类型,而 interface 不行 2、type 语句中还可以使用 typeof 获取实例的 类型进行赋...
interfacePerson{name:string;gender:boolean;age?:number;[propname:string]:any;running(type:string):void;}classStudentimplementsPerson{[propname:string]:any;name!:string;gender!:boolean;age?:number|undefined;running(type:string):void{console.log(type);}}constjones:Student={name:"jones",gender:false...
1. interface简介 interface是对象的模板,可以看作是一种类型约定,中文译为接口,使用了某个模板的对象,就拥有了指定的类型结构。 指定了一个对象模板,有三个属性,任何要实现这个接口的对象,都必须部署这三个属性,并且符合规定的类型。 interface Person { ...
interface Calculate { add(x: number, y: number): number multiply: (x: number, y: number) => number } 6. 可索引类型 可索引类型接口读起来有些拗口,直接看例子: // 正常的js代码 let arr = [1, 2, 3, 4, 5] let obj = { brand: 'imooc', type: 'education' } arr[0] obj['brand...
typeScript 接口interface 在面向对象语言中,接口是一个很重要的概念,它是对行为的抽象。接口也叫 interface 。 在js 中没有接口这个概念,它是新增的。该如何定义呢?下面来一起学习吧 1、接口定义 接口的作用: 在面向对象编程中,接口是一种规范的定义,它定义了行为和动作规范; 在程序设计内,接口起到一种限制和...
typescript class 类和interface接口 在接触 ts 相关代码的过程中,总能看到 interface 和 type 的身影。写代码感觉谁像是一堆亲兄弟,相同的功能用哪一个都可以实现。但最近总看到他们,就想深入的了解一下他们。 1.interface:接口 TypeScript 的核心原则之一是对值所具有的结构进行类型检查。 而接口的作用就是为...
// Interface 不支持基本类型别名 interface StringType = string; // 错误:不能使用 // Type 支持基本类型别名 type StringType = string; // 正确 type NumberArray = number[]; type Callback = (data: string) => void; 1. 2. 3. 4. 5. 6. 7. 联合类型 // Interface 不能直接定义联合类型 ...
interface 是对象的模板,可以看作是一种类型约定,中文译为“接口”。使用了某个模板的对象,就拥有了指定的类型结构。 interface Person { firstName: string; lastName: string; age: number; } 上面示例中,定义了一个接口Person,它指定一个对象模板,拥有三个属性firstName、lastName和age。任何实现这个接口的对...