ts的联合类型
- 联合类型 关键字符 |
let age:string | number = '18'
age = 18
- 类型缩小
function printArgument(id:string,number) {
if(typeof id === "string"){
console.log(id.length);
}
}
ts中定义接口
interface IPerson {
name:string,
age:number
idCard?:number
}
type person = {
name:string,
age:number
idCard?:number
}
type 与 interface区别
- type比interface定义的范围更广; 接口只能用来声明对象
- 在声明对象时, interface可以多次声明; 并且会合并
- type不允许两个相同名称的别名同时存在;
- interface支持继承
- 如果是非对象类型的定义使用type, 如果是对象类型的声明那么使用interface
ts中的交叉类型 &
- 俩种类型同时满足 A&B
interface A {
name:string
}
interface B {
age:number
}
type ABToghter = A & B;
//info 必须同时满足A B 俩个接口
const info:ABToghter = {
name:'lxl',
age:18
}
ts 的类型断言
- 给某个变量指定特定的类型
- 断言只能断言成更加具体的类型, 或者 不太具体(any/unknown) 类型
const name1: string = 'lxl';
const name2 = name1 as any;
const name3 = name2 as string;
ts 非空类型断言
- 关键字 !
- 可选链 mdn 可选链运算符(?.) - JavaScript | MDN (mozilla.org)
interface IPerson {
name: string
age: number
friend?: {
name: string
}
}
const info: IPerson = {
name: "why",
age: 18
}
console.log(info.friend)
console.log(info?.friend)
if(info?.friend) {
console.log(info.friend)
}
if(info!.friend) {
console.log(info.friend)
}
ts 的字面量类型
const name: "lxl" = "lxl"
let age: 18 = 18
// 2.将多个字面量类型联合起来 |
type Orientation = "east" | "south" | "west" | "north"
const o1: Orientation = "north"