заметки об исследовании 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))
По умолчанию, когда круг равен true, радиус должен существовать.
перегрузка функции
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()
Расширенный тип
Записывать
Тип атрибута находится слева, а значение — справа.
Выбирать
В левой части показаны выбираемые атрибуты, а в правой — выбранные атрибуты.
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
Пропускать
Слева — выбираемые атрибуты, справа — атрибуты, которые необходимо отфильтровать.
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,
}
Исключать
Пересечение
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.
Извлекать
Пересечение
fields: Array<Extract<keyof T, keyof K>>
Смысл в том, чтобы взять поля, общие для T и K
Тип возврата
Используется для создания типа, содержащего возвращаемое значение функции 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;
// }