与 type 和 interface 不同的是 class 定义的类型信息会保存在编译后的代码中。 classUser{name: string;age: number;constructor(name: string, age: number) {this.name= name;this.age= age; }sayHello():void{console.log(`Hello, my name is${this.name}`); } }classEmployeeextendsUser{role: stri...
同时,接口也可以多重继承。 1 interface Animal { 2 name: string; 3 eat(): void; 4 } 5 6 interface Person extends Animal { // 继承自Animal接口 7 use(): void; 8 } 9 10 class People implements Person { 11 name: string; 12 constructor(theName: string) { 13 = theName; 14 } 15 ...
4:接口非必选值得定义 正常接口(interface)中定义的变量是必须被继承的,但是,在正常使用的时候,很可能有一些变量是非必需的,其实typeScript已经为我们准备好了相应的办法,就是在 : 号前加一个 ? 比如把person的接口写成这样。 interface person{ name:string, age:number, height:number, waistline?: number } ...
interfacePerson{name:string; age?:number; [propName:string]:string; }lettom:Person= {name:'Tom',age:25,gender:'male'};// index.ts(3,5): error TS2411: Property 'age' of type 'number' is not assignable to string index type 'string'.// index.ts(7,5): error TS2322: Type '{ [...
interface UserInterface{ [index:number]:string } let arr:UserInterface = ['aa','bb'] interface UserInterface2{ [index:string]:string } let obj:UserInterface2 = {name:"sss"} 通过接口约束构造函数 代码语言:javascript 代码运行次数:0 运行 AI代码解释 class Animal3{ constructor(public name:stri...
interface AnimalLink {eat(): void; move(): void } AI代码助手复制代码 接口可以实现继承 interfacePersonLikeextendsAnimalLink{speak():void}classPerson2implementsPersonLike{speak() { };eat() { };move() { } } AI代码助手复制代码 通过接口约束变量类型 ...
15 class 使用 interface616 播放时尚界公主 收藏 下载 分享 手机看 登录后可发评论 评论沙发是我的~选集(20) 自动播放 [1] 1 使用typescript来约束... 1002播放 04:36 [2] 1 一个例子让你明白泛型是什么 1087播放 03:17 [3] 2 public 修饰符 894播放 03:24 [4] 2 typescript 中 ...
interface PersonLike extends AnimalLink {speak(): void}class Person2 implements PersonLike {speak() { };eat() { };move() { }} 1. 2. 3. 4. 5. 6. 7. 8. 通过接口约束变量类型 复制 interface Person3 {readonly id: number;name: string;[PropName: string]:any}let p1: Person3 = ...
class Point { x = 0; y = 0; } const pt = new Point(); // Prints 0, 0 console.log(`${pt.x}, ${pt.y}`); 就像const、let和var,一个类属性的初始值会被用于推断它的类型: const pt = new Point(); pt.x = "0"; // Type 'string' is not assignable to type 'number'. ...
接下来,我们通过一个接口来扩展以上实例,创建一个 interface.ts 文件,修改index.html的 js 文件为interface.js。 interface.js 文件代码如下: interfaceShape{name:string;width:number;height:number;color?:string;}functionarea(shape:Shape){vararea=shape.width*shape.height;return"I'm "+shape.name+" with ...