话不多说直接看例子
interface Bird{
fly: Boolean;
sing: ()=>{}
}
interface Dog{
fly: Boolean;
bark: ()=>{}
}
function trianAnimal(animal: Bird|Dog){
if (animal.fly){
(animal as Bird).sing()
}
(animal as Dog).bark()
}
function trianAnimal2(animal: Bird|Dog){
if ("sing" in animal){
animal.sing()
}else{
animal.bark()
}
}
function add(first: string|number, second: string|number){
if(typeof first === "string" || typeof second === "string"){
return `${first}${second}`
}else{
return first+second
}
}
function add2(first: object|aaa, second: object|aaa){
if(first instanceof aaa && second instanceof aaa){
return first.count+second.count
}else{
return 0
}
}
keyof
interface Person {
name: string;
age: number;
gender: string;
}
class Teacher {
constructor(private info: Person) {}
getInfo<T extends keyof Person>(key: T): Person[T] {
return this.info[key];
}
}
const teacher = new Teacher({
name: 'dell',
age: 18,
gender: 'male'
});
const test = teacher.getInfo('name');
console.log(test);
enum 枚举类型
enum Status {
OFFLINE,
ONLINE,
DELETED
}
function getResult(status: any) {
if (status === Status.OFFLINE) {
return 'offline';
} else if (status === Status.ONLINE) {
return 'online';
} else if (status === Status.DELETED) {
return 'deleted';
}
return 'error';
}
const result = getResult(1);
console.log(result);
const result1 = getResult(Status.OFFLINE);
console.log(result1);
enum Status {
OFFLINE = 1,
ONLINE,
DELETED
}
function getResult(status: any) {
if (status === Status.OFFLINE) {
return 'offline';
} else if (status === Status.ONLINE) {
return 'online';
} else if (status === Status.DELETED) {
return 'deleted';
}
return 'error';
}
const result = getResult(1);
console.log(result);
const result1 = getResult(Status.OFFLINE);
console.log(result1);
const result2 = getResult(2);
console.log(result2);
console.log(Status.OFFLINE)
console.log(Status.ONLINE)
console.log(Status.DELETED)
console.log(Status.OFFLINE, Status[0]);
console.log(Status[1]);