TS 学习笔记
语法
非空断言
属性后面加!
interface Shape {
kind: 'circle' | 'square'
radius?: number
sideLength?: number
}
function getArea(shape: Shape) {
if (shape.kind == 'circle') {
return Math.PI * shape.radius! ** 2 // 圆的面积公式 S=πr²
}
return 6666
}
const shape: Shape = {
kind: 'circle',
radius: 54,
}
console.log(getArea(shape))
默认 circle 为真时,radius 一定存在
函数重载
function makeDate(timestamp: number): Date
function makeDate(m: number, d: number, y: number): Date
function makeDate(mOrTimestamp: number, d?: number, y?: number): Date {
if (d !== undefined && y !== undefined) {
return new Date(y, mOrTimestamp, d)
} else {
return new Date(mOrTimestamp)
}
}
const d1 = makeDate(12345678)
const d2 = makeDate(5, 5, 5)
const d3 = makeDate(1, 3)
// No overload expects 2 arguments, but overloads do exist that expect either 1 or 3 arguments.
拥有任意属性的对象
可以使用对象索引签名声明、Record 工具类两种方法
// 1.对象索引签名
interface CustomObject {
[key: string]: string
}
function fn1(data: CustomObject) {
console.log(data)
}
// 2.使用 Record 工具类
function fn2(data: Record<string, any>) {
console.log(data)
}
fn1(1)
fn1('')
fn1()
fn1({
name: 'zs' })
fn1({
age: 13 })
fn2(1)
fn2('')
fn2()
fn2({
name: 'zs' })
fn2({
age: 13 })
交叉类型
使用 & 链接
interface Colorful {
color: string
}
type ColorfulSub = Colorful & {
color: number
}
类型导入导出
// @filename: animal.ts
export type Cat = {
breed: string; yearOfBirth: number }
// 'createCatName' cannot be used as a value because it was imported using 'import type'.
export type Dog = {
breeds: string[]; yearOfBirth: number }
export const createCatName = () => 'fluffy'
// @filename: app.ts
import {
createCatName, type Cat, type Dog } from './animal.js'
const name = createCatName()
高级类型
Record
左侧为属性类型,右侧为值
Pick
左侧为可选择的属性,右侧为选择好的属性
interface Todo {
title: string
description: string
completed: boolean
}
type TodoPreview = Pick<Todo, 'title'>
const todo: TodoPreview = {
title: 'Clean room',
completed: false,
}
todo.completed
// const todo: TodoPreview
Omit
左侧为可选择的属性,右侧为需过滤掉的属性
interface Todo {
title: string
description: string
completed: boolean
createdAt: number
}
type TodoPreview = Omit<Todo, 'description'>
const todo: TodoPreview = {
title: 'Clean room',
completed: false,
createdAt: 1615544252770,
}
Exclude
取交集
type T0 = Exclude<'a' | 'b' | 'c', 'a'>
// type T0 = "b" | "c"
type T1 = Exclude<'a' | 'b' | 'c', 'a' | 'b'>
// type T1 = "c"
type T2 = Exclude<string | number | (() => void), Function>
// type T2 = string | number
含义是取 T 和 K 未共有的字段
Extract
取交集
fields: Array<Extract<keyof T, keyof K>>
含义是取 T 和 K 共有的字段
ReturnType
用于构造一个含有 Type 函数的返回值的类型。
declare function f1(): {
a: number; b: string }
type T0 = ReturnType<() => string>
// type T0 = string
type T1 = ReturnType<(s: string) => void>
// type T1 = void
type T2 = ReturnType<<T>() => T>
// type T2 = unknown
type T3 = ReturnType<<T extends U, U extends number[]>() => T>
// type T3 = number[]
type T4 = ReturnType<typeof f1>
// type T4 = {
// a: number;
// b: string;
// }