TS(一)Types

翻译自: 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
}>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值