private _name: string; constructor(name: string){ this._name = name; } get name(){ return this._name; } set name(name: string){ this._name = name; } } const p1 = new Person('孙悟空'); console.log(p1.name); // 通过getter读取name属性 p1.name = '猪八戒'; // 通过setter修...
一个更高级的例子,使用原型属性推断并约束构造函数与类实例的关系。 classBeeKeeper{hasMask:boolean;}classZooKeeper{nametag:string;}classAnimal{numLegs:number;}classBeeextendsAnimal{keeper:BeeKeeper;}classLionextendsAnimal{keeper:ZooKeeper;}functioncreateInstance<AextendsAnimal>(c:new()=>A):A{returnnewc();...
getProperty(x,"a");//x 里有 a 属性getProperty(x,"m");//报错,x 里没有 m 属性。Argument of type '"m"' is not assignable to parameter of type '"a" | "b" | "c" | "d"'.
泛型类与泛型接口类似,使用>括起泛型类型,紧跟类名。GenericNumber类的使用直观,并且可能注意到它不限于number类型。也可以使用字符串或其他更复杂类型。与接口一样,直接将泛型类型放在类后面,帮助确认类的所有属性都使用相同的类型。类有两部分:静态部分和实例部分。泛型类指的是实例部分的类型,因此...
nametag: string; } class Animal { numLegs: number; } class Bee extends Animal { keeper: BeeKeeper; } class Lion extends Animal { keeper: ZooKeeper; } function createInstance(c: new () => A): A { return new c(); } createInstance(Lion).keeper.nametag; // typechecks!
classAnimal{constructor(publicname:string){}makeSound():void{console.log("Some generic animal sound");}}letcat=newAnimal("Whiskers");cat.makeSound(); 类型推断: TypeScript通常根据分配的值推断类型,减少了显式类型注释的需求。 示例: 代码语言:typescript ...
nametag: string; } class Animal { numLegs: number; } class Bee extends Animal { keeper: BeeKeeper; } class Lion extends Animal { keeper: ZooKeeper; } function createInstance(c: new () => A): A { return new c(); } createInstance(Lion).keeper.nametag; // typechecks!
letpasscode="Hello TypeScript";classEmployee{private_fullName:string;getfullName():string{returnthis._fullName;}setfullName(newName:string){if(passcode&&passcode=="Hello TypeScript"){this._fullName=newName;}else{console.log("Error: Unauthorized update of employee!");}}}letemployee=newEmployee(...
TypeScript can also infer the type of the generic parameter from the function parameters. ClassesGenerics can be used to create generalized classes, like Map.Example class NamedValue<T> { private _value: T | undefined; constructor(private name: string) {} public setValue(value: T) { this....
get fullName(): string { return this._fullName; } set fullName(newName: string) { if (passcode&& passcode == "Hello TypeScript") { this._fullName = newName; } else { console.log("Error: Unauthorized update of employee!");