TS高级类型
Typescript接口
(function () {
interface myInterface{
name:string,
age:number
}
const obj:myInterface={
name:"张三",
age:12
}
interface myIter{
name:string;
sayHi():void;
}
class myClass implements myIter{
name: string;
constructor(name:string) {
this.name=name
}
sayHi(): void {
console.log("大家好")
}
}
})()
Typescript属性的封装
(function () {
class Person{
private _name:string;
private _age:number;
constructor(name:string,age:number) {
this._name=name
this._age=age
}
get getName(): string {
return this._name;
}
set setName(value: string) {
this._name = value;
}
get getAge(): number {
return this._age;
}
set setAge(value: number) {
if (value>0){
this._age = value;
}
}
}
const person=new Person("张三",14)
person.setName="李四"
person.setAge=-1000
console.log(person)
})()
Typescript泛型
function fu<T>(a:T):T {
return a;
}
let result=fu(11);
let result2=fu<string>("hello")
function fn2<T,K>(a:T,b:K):T {
console.log(b)
return a;
}
fn2<number,string>(123,"hello")
interface Interface {
length:number
}
function fn3<T extends Interface>(a:T):number {
return a.length;
}
fn3("张三");
class MyClass<T> {
name:T;
constructor(name:T) {
this.name=name;
}
}
const mc=new MyClass("张三");