第3章 类型收窄 
typeof 
- 基本数据类型使用 typeof判断类型后,即可收窄类型
ts
const fn = (input: string | number) => {
  if (typeof input === 'string') {
    input.split('-'); // input: string
  } else {
    input.toFixed(2); // input: number
  }
};instanceof 
- 复杂数据类型使用 instanceof判断类型后,即可收窄类型
ts
const fn = (input: Date | number[]) => {
  if (input instanceof Date) {
    input.getTime(); // input: Date
  } else {
    input.length; // input: number[]
  }
};in 运算符 
- in运算符用于确定对象是否具有该属性名
ts
type Circle = {
  radius: number;
};
type Reactangle = {
  width: number;
  height: number;
};
function calculateArea(shape: Circle | Reactangle) {
  if ('radius' in shape) {
    shape.radius; // shape: Circle
  } else if ('width' in shape && 'height' in shape) {
    shape.height; // shape: Reactangle
    shape.width; // shape: Reactangle
  }
}可识别联合 
- 包含一个 type属性,可以用来区分两个不同的联合
ts
type Circle = {
  type: 'circle';
  radius: number;
};
type Reactangle = {
  type: 'reactangle';
  width: number;
  height: number;
};
function calculateArea(shape: Circle | Reactangle) {
  if (shape.type === 'circle') {
    shape.radius; // shape: Circle
  } else if (shape.type === 'reactangle') {
    shape.height; // shape: Reactangle
    shape.width; // shape: Reactangle
  }
}is 谓词 
- is关键字一般用于函数返回值类型中,判断参数是否属于某一类型,并根据结果返回对应的布尔类型
ts
type Circle = {
  type: 'circle';
  radius: number;
};
type Reactangle = {
  type: 'reactangle';
  width: number;
  height: number;
};
function calculateArea(shape: Circle | Reactangle) {
  if (isCircle(shape)) {
    shape.radius; // shape: Circle
  } else if (isReactangle(shape)) {
    shape.height; // shape: Reactangle
    shape.width; // shape: Reactangle
  }
}
function isCircle(shape: Circle | Reactangle): shape is Circle {
  return shape.type === 'circle';
}
function isReactangle(shape: Circle | Reactangle): shape is Reactangle {
  return shape.type === 'reactangle';
}断言 
as 断言
- 定义一个函数,它的返回值是 number或string
- 使用 as可以为其指定类型
- 也可以使用 <>的语法指定类型
ts
const getNumOrStr = (val: number | string) => val;
let val = getNumOrStr(1.999999) as number; // 将 val 指定为 number 类型
let val = <number>getNumOrStr(1.999999) // 也可以使用 <number> 语法
val.toFixed(2); // 此时可以正常调用 number 类型的方法const 断言
- 通过 const声明的变量,类型为严格类型
- 通过 let声明的变量,类型为通用类型
ts
const myName = 'zhichao'; // 类型为 'lbviic'
let yourName = 'zhichao'; // 类型为 string- 使用 as const可以将通用类型转换为严格类型
ts
let myName = 'zhichao' as const; // 类型 'lbviic'
let state = true as const; // 类型 true
// 对象转换会为只读属性,数组转换成为只读元组
let myObj = { name: 'zhichao' } as const; // 类型 { readonly name: 'zhichao'; }
let myArr = [1, true, 'zhichao'] as const; // 类型 readonly [1, true, 'zhichao']非空断言
ts
// "strictNullChecks": true
// el1可能为空,会报错
const el1: HTMLDivElement = document.querySelector('.myDiv'); 
// 通过断言类型可解决报错
const el2: HTMLDivElement = document.querySelector('.myDiv') as HTMLDivElement; 
// 通过非空断言也可以解决报错 最后添加一个 !
const el3: HTMLDivElement = document.querySelector('.myDiv')!;








