交叉類型 &
如果我們需要把兩個不同的對象合并為一個對象,則該對象為這兩個對象的交叉類型
# T & U
const mergeFunc = <T, U>(obj1: T, obj2: U) :T & U => {
return Object.assign(obj1, obj2) as T & U;
}
聯(lián)合類型 |
如果我們需要一個函數(shù)接收number或者string類型,返回值為參數(shù)的長度,那么這個方法的參數(shù)就需要用聯(lián)合類型來描述
// string | number
const getLengthFunc = (content: string | number) : number => {
if(typeof content === "string") return content.length;
else {
return content.toString().length;
}
}
字面量類型
字面量類型中包括字符串字面量、數(shù)字字面量
字符串字面量
type str = "hello"
const name: str = "hello";
// 一旦指定了name的類型為str,那么它(name)只能用 'hello'作為變量name的值
type Direction = 'north' | 'west' | 'south' | 'east'

例:字符串字面量
數(shù)字字面量
type Age = 18;
interface Person {
name: String,
age: Age
}
const p1 : Person = {
name: "any string",
age: 18 // 這塊只能寫18
}

例:數(shù)字字面量
可辨識聯(lián)合
兩要素
1.具有普通的單例類型屬性(作為辨識特征)
2.一個類型別名包含了哪些類型的聯(lián)合
interface Square {
kind: 'square',
size: number
}
interface Rectangle {
kind: 'rectangle',
width: number,
height: number
}
interface Circle {
kind: 'circle',
radius: number
}
type Shape = Square | Rectangle | Circle
const getShapeArea = (s: Shape): number => {
switch(s.kind) {
case 'circle': return Math.PI * s.radius * s.radius;
case 'rectangle': return s.width * s.height / 2;
case 'square': return s.size * s.size;
}
}

例:可辨識聯(lián)合
索引類型
1.索引類型查詢 keyof
interface info {
name: string,
age: number
}
let infoprop: keyof info;
// 那么infoprop就只能定義為 info接口下定義的字段
infoprop = 'name'; // ok
infoprop = 'age'; // ok
infoprop = 'gender'; // error

例:索引類型
2.索引訪問操作符[]
通過 [] 索引類型訪問操作符, 我們就能得到某個索引的類型

索引類型訪問操作符.jpg
類型如果為null、undefined、never,則不會被訪問到
interface Type {
a: string;
b: never;
c: boolean;
d: number;
e: object;
f: null;
g: undefined
}
type Test = Type[keyof Type];
let prop: Test =
