接口
(function () {
type myType = {
name: string;
age: number;
[propName: string]: any;
};
interface myInterface {
name: string;
age: number;
}
interface myInterface {
[propName: string]: any;
}
const obj: myType = {
name: "XX",
age: 18,
gender: "man",
};
const obj2: myInterface = {
name: "XX",
age: 18,
gender: "man",
};
interface myInter {
name: string;
sayHello(): void;
}
class MyClass implements myInter {
name: string;
constructor(name: string) {
this.name = name;
}
sayHello() {
console.log(this.name + "大噶好~~");
}
}
const my = new MyClass("大柱");
my.sayHello();
})();
8、属性的封装
(function () {
class Person {
private _name: string;
private _age: number;
constructor(name: string, age: number) {
this._name = name;
if (age > 0) {
this._age = age;
} else {
throw new Error("年龄不合法");
}
}
getName() {
return this._name;
}
setName(newName: string) {
this._name = newName;
}
get age() {
return this._age;
}
set age(newAge: number) {
if (newAge > 0) {
this._age = newAge;
}
}
}
const person = new Person("XX", -18);
console.log(person);
console.log(person);
person.setName("YY");
person.age = 88;
console.log(person);
})();
语法糖
class A {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
等价于
class A {
constructor(public name: string, public age: number) {}
}
9、泛型
function fn<T>(a: T): T {
return a;
}
let result = fn(10);
let result2 = fn<string>("hello");
function fn2<T, K>(a: T, b: K): T {
console.log(b);
return a;
}
fn2<number, string>(123, "hello");
interface Inter {
length: number;
}
function fn3<T extends Inter>(a: T): number {
return a.length;
}
fn3("1234");
class MyClass<T> {
name: T;
constructor(name: T) {
this.name = name;
}
}
const my = new MyClass<string>("XX");