typescript - 2
程序员文章站
2022-05-14 13:28:24
...
补充
# undefined和null都是其他数据类型的子集
let str:string = "ddd";
str = undefined // 不会报错
# 如果不指定类型,那默认是any,后续的任何类型的赋值操作都允许而不会类型检查
let b;
b = 1;
b = "fsss";
# 联合数据类型注意点:其中toString是string和number都拥有的,不然不允许
let demo:string | number;
console.log(demo.toString());
# 剩余参数, 其中剩余参数的类型一定是any,只读属性一旦赋值便不能修改
interface Istate {
age:number,
readonly name: string,
[arg:string]: any
}
let obj1:Istate = {
age: 10,
name: '你好'
}
# 数组声明的三种表示方法
- let arr:number [] = [1, 2, 3];
- let arrType: Array<number> = [1, 2, 3];
- interface IArr {
[index: number]:number
}
interface Istate {
username: string,
age: number
}
let arrType4:IArr = []
let arrType5: Array<Istate> = [{
username: '张三',
age: 90
}]
let arrType6: Istate[] = [{ username: '张三', age: 90 }]
# 函数约束
- let funcType1:(name: string, age: number) => number = function (name: string, age:number):number{}
- interface funcType6 {
(name: string, age:number):number
}
let funcType6: funcType6 = function (name: string, age:number):number{}
# 类型断言不是类型转换,只能断言联合类型里存在的类型
推荐阅读