TS-5
2023-03-13 本文已影响0人
RickyWu585
- 交叉类型
&
:交集
type A = string & number // never




- interface使用extends的话,发现有类型冲突会直接冲突,因此在定义可扩展的类型时最好用interface
- 函数的交集会得到参数的并集
type A = {
method: (n:string) => void
}
type B = {
method: (n:number) => void
} & A
const x:B = {
// n:string | number
method:(n)=>{
console.log(n);
}
}
----------------------------------------
type Fn1 = (n:string) => void
type Fn2 = (n:number) => void
type Fn = Fn1 & Fn2
// n: string | number
const fn: Fn = (n)=> console.log();
- 具体理解
|
,ts声明时检查紧,赋值时检查松
type A = {
name: string
}
type B = {
age: number
}
type C = A | B
// 都正确
const p:C = {name:'x'}
const p:C = {age: 12}
// error,不能有gender属性
const x:C = {
name:'',
age: 12,
gender: ''
}
------------------------------------
// 不报错
const d = {
name: '',
age: 12,
gender: ''
}
const p:C = d