typeof

  1. const defaultOrder = {
  2. articles: [
  3. {
  4. price: 1200.50,
  5. vat: 0.2,
  6. title: 'Macbook Air Refurbished - 2013'
  7. },
  8. {
  9. price: 9,
  10. vat: 0,
  11. title: 'I feel smashing subscription'
  12. }
  13. ],
  14. customer: {
  15. name: 'Fritz Furball',
  16. address: {
  17. city: 'Smashing Hill',
  18. zip: '90210',
  19. street: 'Whisker-ia Lane',
  20. number: '1337'
  21. },
  22. dateOfBirth: new Date(2006, 9, 1)
  23. }
  24. }

我们有一个复杂的对象,想把这个对象作为一个通用的类型,为了不写冗长的类型声明,我们可以使用typeof提取对象类型

  1. type Order = typeof defaultOrder
  2. function checkOrders(orders: Order[]) {
  3. let valid = true;
  4. for (let order of orders) {
  5. valid = valid && order.articles.length > 0
  6. }
  7. return valid
  8. }

如果你更新了对象defaultOrder,类型Order也会跟着更新

Optional Properties

如果我们希望一个对象的属性是可选的,则使用问号

  1. type Article = {
  2. title: string,
  3. price: number,
  4. vat: number,
  5. stock?: number,
  6. description?: string
  7. }

Exporting and Importing Types

如果我们不想重复声明类型,可是使用module
导出类型

  1. export type Article = {
  2. title: string,
  3. price: number,
  4. vat: number,
  5. stock?: number,
  6. description?: string
  7. }

导入类型

  1. import { Article } from './example-two'
  2. const book: Article = {
  3. price: 29,
  4. vat: 0.2,
  5. title: 'Another book by Smashing Books'
  6. }

如果我们只对类型感兴趣,可以在import后加上type

  1. import type { Article } from './example-two'
  2. const book: Article = {
  3. price: 29,
  4. vat: 0.2,
  5. title: 'Another book by Smashing Books'
  6. }