2. type 定义类型 & 类型断言

91 阅读1分钟
// type 可以定义一种新类型 
type Direction = 'up' | 'down' | 'left' | 'right'
let direction:Direction = 'up'

type women = {
    wealthy:true,
    waste:string
} | {
    wealthy:false,
    norality:string
}

let richWoman:women = {
    wealthy:true,
    waste:"购物消费"
}
- 断言的问题
let strOrNum: string | number
strOrNum = '1' 也可能是 strOrNum = 1
strOrNum.endsWith() // Property 'endsWith' does not exist on type 'number'.
strOrNum.toFixed() // Property 'toFixed' does not exist on type 'string'.

- 类型断言后再使用
let strOrNum: string | number
strOrNum = '1';
(strOrNum as number).toFixed() // Conversion of type 'string' to type 'number' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.

翻译:将类型“string”转换为类型“number”可能会出错,因为这两种类型都没有与另一种类型充分重叠。如果这是故意的,请先将表达式转换为“未知”。

let strOrNum: string | number
strOrNum = '1';
(strOrNum as unknown as number).toFixed() // 没有报错
// 断言
// 1. 非空断言 !.
let ele = document.getElementById("app") // HTMLElement | null
ele.innerHTML = "hello world" // ts 报错 'ele' is possibly 'null'
ele!.innerHTML = "hello world" // 这个值一定不为空 (ts非空断言)
console.log(ele!.innerHTML)

- js ?.
let ele = document.getElementById("#app")
ele?.innerHTML = "hello world" // 赋值表达式的左侧不能是可选的属性访问。

let ele = document.getElementById("#app")
ele?.innerHTML = "hello world" // 报错:赋值表达式的左侧不能是可选的属性访问。
console.log(ele?.innerHTML) // 没有报错 可选链

null || 1 或者 false || 1 // 第一个值为假则走后面的逻辑
??(空值合并操作符) 如果前一个值不是 null 或者 undefined 则返回第一个值,否则返回第二个
false ?? 1 // false
1 ?? 2 // 1
null ?? 2 // 2

2. as 断言:强制把某一个类型断言成已经存在的某一个类型,as 直接写在变量后面。
let ele = document.getElementById("app"); // HTMLElement | null
(ele as HTMLElement).style.background = 'red';

3. 双重断言
// 一个值断言成 any 再断言成某一个类型,any 类型可以赋值给任意类型
let str:string | number = 123;
(str as any as boolean) = true