引言 七种非常有用的 TypeScript 类型,包括获取对象类型、函数返回类型、嵌套类型的查看、可选属性和排除属性等。 typeof
const obj = {
name: "yiyun",
age: 16
}
type Person = typeof obj
keyof
const obj = {
name: "yiyun",
age: 16
}
type Person = keyof typeof obj
ReturnType
const func = () => {
const val = "string"
return val
}
type Return = ReturnType<typeof func>
添加 async
const func = async () => {
const val = "string"
return val
}
type Return = ReturnType<typeof func>
添加 Awaited<T>
const func = async () => {
const val = "string"
return val
}
type Return = Awaited<ReturnType<typeof func>>
Prettify<NestedType>
interface MainType {
name: string,
age: number
}
type NestedType = MainType & {
isDeveloper: boolean
}
如图,这么做, 不易看, 只能看到局部
interface MainType {
name: string,
age: number
}
type NestedType = MainType & {
isDeveloper: boolean
}
type Prettify<T> = {
[K in keyof T]: T[K]
} & {}
type idk = Prettify<NestedType>
现在可以看到全部了, 非常完整易看 Partial<T> 与 Required<T>
interface Todo {
title: string,
description: string
}
// Partial<Todo> 的作用 等同于 下方 , 使其所有字段都变成 可选
// interface Todo {
// title?: string,
// description?: string
// }
const updateTodo = (todo: Todo, fieldsToUpdate: <Todo>) => {
return { ...todo, fieldsToUpdate }
}
const initialTodo: Todo = {
title: "洗碗",
description: "锅留着下次再洗"
}
const updatedTodo = updateTodo(initialTodo, {})
现在 title 与 description 都变成可选了, 以至于可传空对象 {}
这不是我们所期望的, 因此将 Partial 改为与之相反的 Required
interface Todo {
title: string,
description: string
}
// Required<Todo> 的作用 会使得其中所有都成为必需
const updateTodo = (todo: Todo, fieldsToUpdate: Required<Todo>) => {
return { ...todo, fieldsToUpdate }
}
const initialTodo: Todo = {
title: "洗碗",
description: "锅留着下次再洗"
}
const updatedTodo = updateTodo(initialTodo, {})
注意: 最初 可选(?) , 再加上 Required , 那么最终是 必需 的
Omit<T, K extends string | number | symbol> 与 Exclude
interface Todo {
title: string,
description: string
}
const todo: Todo = {
title: "",
description: ""
}
type Omitted = Omit<Todo, "title">
添加一个 createdAt
interface Todo {
title: string,
description: string,
createdAt: Date
}
// const todo: Todo = {
// title: "",
// description: ""
// }
type Omitted = Omit<Todo, "createdAt">
对于复杂情况, Omit 不总是适用
type Shapes =
| {
kind: "circle",
radius: number
}
| {
kind: "square",
x: number
}
type Omitted = Omit<Shapes, { kind: "circle" }>
因此我们不要使用它来排除
type Shapes =
| {
kind: "circle",
radius: number
}
| {
kind: "square",
x: number
}
type Omitted = Exclude<Shapes, { kind: "circle" }>
Q&A 补充 参考 感谢帮助! 7 Awesome TypeScript Types You Should Know - YouTube