typeof
const defaultOrder = {
articles: [
{
price: 1200.50,
vat: 0.2,
title: 'Macbook Air Refurbished - 2013'
},
{
price: 9,
vat: 0,
title: 'I feel smashing subscription'
}
],
customer: {
name: 'Fritz Furball',
address: {
city: 'Smashing Hill',
zip: '90210',
street: 'Whisker-ia Lane',
number: '1337'
},
dateOfBirth: new Date(2006, 9, 1)
}
}
我们有一个复杂的对象,想把这个对象作为一个通用的类型,为了不写冗长的类型声明,我们可以使用typeof提取对象类型
type Order = typeof defaultOrder
function checkOrders(orders: Order[]) {
let valid = true;
for (let order of orders) {
valid = valid && order.articles.length > 0
}
return valid
}
如果你更新了对象defaultOrder,类型Order也会跟着更新
Optional Properties
如果我们希望一个对象的属性是可选的,则使用问号?
type Article = {
title: string,
price: number,
vat: number,
stock?: number,
description?: string
}
Exporting and Importing Types
如果我们不想重复声明类型,可是使用module
导出类型
export type Article = {
title: string,
price: number,
vat: number,
stock?: number,
description?: string
}
导入类型
import { Article } from './example-two'
const book: Article = {
price: 29,
vat: 0.2,
title: 'Another book by Smashing Books'
}
如果我们只对类型感兴趣,可以在import后加上type
import type { Article } from './example-two'
const book: Article = {
price: 29,
vat: 0.2,
title: 'Another book by Smashing Books'
}