交叉类型
interface A {
name: string;
}
interface B {
age: number;
}
interface C extends A, B {
gender: string;
}
// 通过类型别名实现
type D = A & B & C
let d: D = {
name: 'hello',
age: 18,
gender:"男"
}
联合类型
type DD = string | number
let d:(string | number)[] = [1,2,'3']
类型保护
function getVal(): string | number {
return Math.random() > 0.5 ? "hello" : 100;
}
let val = getVal();
if (typeof val === "string") {
console.log("当前是string类型并且长度为" + val.length)
} else {
console.log("当前是number类型并且值为" + val)
}
可辨识联合
interface Circle {
radius: number
kind: "circle"
}
interface Square {
width: number
kind: "square"
}
type Shape = Circle | Square
function getArea(shape: Shape) {
if (shape.kind === 'square') {
return shape.width * shape.width
} else {
return Math.PI * shape.radius ** 2
}
}
const circle: Circle = {
kind: "circle",
radius: 10
}
const square: Square = {
kind: "square",
width: 10
}
console.log(getArea(circle))
console.log(getArea(square))
索引访问操作符
interface Dadong{
name: string;
age: number;
}
type Dadongtype = Dadong['name']
索引类型查询
const aobj = {
aa: "1",
bb: 2
}
function getObjVal<T,K extends keyof T>(obj:T,key:K):T[K]{
return obj[key];
}
getObjVal(aobj,"aa");