翻译自: https://ts.chibicode.com/todo
自学记录!!
分为三部分:
Section 1: Types, Read-only Properties, and Mapped Types
Section 2: Array Types, Literal Types, and Intersection Types
Section 3: Union Types and Optional Properties
Section 1
type Todo = {
readonly id: number
readonly text: string
readonly done: boolean
}
function toggleTodo(todo: Todo): Todo {
return {
// This line was missing
id: todo.id,
text: todo.text,
done: !todo.done
}
}
除了挨个加readonly, 还可以像以下这样, 是每一个都是 只读 属性
type Foo = {
bar: number
}
type ReadonlyFoo = Readonly<Foo>
// ReadonlyFoo is { readonly bar: number }
所以以上也可以写成
// Readonly<...> makes each property readonly
type Todo = Readonly<{
id: number
text: string
done: boolean
}>
Section 2: Array Types, Literal Types, and Intersection Types
全选功能:
type Todo = Readonly<{
id: number
text: string
done: boolean
}>
type CompletedTodo = Readonly<{
id: number
text: string
done: true // You can use exact values when specifying a type. This is called literal types.
}>
function completeAll(
todos: readonly Todo[]
): CompletedTodo[] {
return todos.map(todo => ({
...todo,
done: true
}))
}
Intersection Types:
type A = { a: number }
type B = { b: string }
// This intersection type…
type AandB = A & B
// …is equivalent to:
type AandB = {
a: number
b: string
}
如果用相同属性,会覆盖
// They booth have a property foo,
// but B’s foo (true) is
// more specific than A’s foo (boolean)
type A = { foo: boolean }
type B = { foo: true }
// This intersection type…
type AandB = A & B
// …is equivalent to:
type AandB = { foo: true }
所以 CompletedTodo 可以改写为:
type Todo = Readonly<{
id: number
text: string
done: boolean
}>
// Override the done property of Todo
type CompletedTodo = Todo & {
readonly done: true
}
Section 3: Union Types and Optional Properties
Union Types :
// Creates a union type of number and string
type Foo = number | string
// You can assign either a number or a string
// variable to Foo. So these will both compile:
const a: Foo = 1
const b: Foo = 'hello'
type Place = 'home' | 'work' | { custom: string };
type Todo = Readonly<{
id: number
text: string
done: boolean
place: Place
}>
Optional Properties: 就是加一个? 表示非必须
type Foo = {
// bar is an optional property because of "?"
bar?: number
}
// These will both compile:
// bar can be present or missing
const a: Foo = {}
const b: Foo = { bar: 1 }
type Place = 'home' | 'work' | { custom: string }
type Todo = Readonly<{
id: number
text: string
done: boolean
// place is optional
place?: Place
}>