赋值兼容检查
interface Person {
name: string,
age: number
}
interface Person2 {
name: string,
}
let x: Person;
let y: Person2;
y = x; //可以执行 x里面有y需要的属性
x = y; //报错 y里面没有x需要的属性
函数传参类型检查
interface Person{
name:string
}
function greet(n:Person){
return n.name
}
const y = {name:'joy',age:12};
greet(y); //可以多不能少
函数赋值参数兼容
let add = function (num1:number,num2:number,num3:number) {
};
let add2 = function (num1:number,num2:number) {
};
add = add2; //多参数的可以替换为少参数的
add2 = add; //报错,少参数的不能替换为多参数的
函数赋值返回值兼容
let getData = () => ({name:'joy',age:12});
let getData2 = () => ({name:'joy'});
getData = getData2; //报错少参数不能代替多参数
getData2 = getData; //多参数可以代替少参数
枚举
enum Direction{
up,
down
}
enum Status{
true,
false
}
let status = Status.true;
status = Direction.up; //报错,不属于一个枚举类
类
class Person{
name:string,
age:number
}
class Animal{
age:number
}
let people:Person;
let animal:Animal
people = animal; //报错,会检验animal里面是否有Person所有属性
animal = people //可以,people里面有animal的age属性
泛型
function getData<T>(data:T):T{
return data;
}
let a:getData<number>;
let b:getData<string>;
a = b;//都可以同个泛型
b = a; //都可以同个泛型
自行回顾
- 赋值兼容检查
- 函数传参类型检查
- 函数赋值参数兼容
- 函数赋值返回值兼容
- 枚举
- 类
- 泛型
网友评论