本文將提供使用typescript高級類型(Record,Partial,Required,Pick , Omit)如何在react中使用的示例。
1. Record
typeScript2.1引入一個內置對象類型是Record,他允許創建類型化映射,并且非常適合創建復合接口,變量的類型必須為Record, 我們必須將字符串作為key傳遞,并且對應的值傳遞某種類型,最簡單的情況是當有一個字符串作為值:
const SERVICES = Record<string, string> = {
doorToDoor: 'delivery at door',
airDelivery: 'flying in',
specialDelivery: 'special delivery',
inStore: 'in-store pickup'
}
解析代碼:聲明一個SERVICES的常量,類型是Record<key, value>類型,key必須是string, value值的類型是字符串
使用Record的一種常見情況是將業務實體的接口作為鍵值保存在字典中。
舉例:創建一個購物車的模型。
export interface ProductInCart {
id: string,
name: string,
amount: number;
label?:string
}
export class CartNodel {
products: Record<string, ProductInCart> = {}
error?:Error = undefined
}
解析代碼:定義了一個ProductInCart接口, 規定了id,name,label是string類型, amount是number類型,聲明了一個cartNodel類里的products變量是Record<string,ProductInCart>, key是string類型,value的值是ProductInCart類型
另外,ts不允許我們為一些定義好的形狀創建一個空對象然后用屬性填充它,但是Record可以解決這個問題,也可以使用字符串enum作為類型中的鍵。
例如, 我們將使用ErrorsEnum來保存和訪問可能錯誤值(消息)
export enum ErrorsEnum {
NetWorkError = 'NetworkError',
ServerError = 'ServerError',
FormValidationErrod = 'FormValudationError',
UnknowError = 'UnkownError'
}
export type CartErrors = Partial<Record<ErrorsEnum, string>>;
export class CartModel {
products: Record<string,ProductInCart> = {};
errors?:CartErrors;
}
解析代碼: 創建了一個ErrorsEnum的枚舉類型, export type CartErrors 定義鍵值對結構的對象 Partial<Record<ErrorsEnum,string>>,Partial的類型是Record<ErrorsEnum, string>, Record里面的key是字符串類型的enum, value的類型是字符串類型
在Material-UI庫中使用Record進行類型增強, 我們可以使用css-in-JS表示法添加自定義樣式,并通過withStyles HOC將其注入,可以把樣式定義一個函數,我們可以將樣式定義為以theme作為參數, 并返回className具有對應樣式的函數,為這個函數定義類型:
import { Theme } from '@material-ui/core';
import { CSSProperties } from '@material-ui/core/styles/withStyles';
export const styles: (theme: Theme) => Record<string, CSSProperties> = (theme) => ({
card: {
...theme.mixins.flexColumn,
width:'100%',
height: 'auto',
} as CSSProperties,
button: {
margin: theme.spacing.unit,
} as CSSProperties,
})
解析代碼: 基本的Record格式: const abc:Record<string, string> = {} ,聲明一個styles的常量, 類型是Record<string, CSSProperties>,后面是一個箭頭函數,參數為theme, 返回一一個對象, 對象里就是Record value的數據類型
你可能會注意到, as CSSProperties 為每個樣式對象添加這些內容會比較麻煩。或者,我們可以利用Record類型的優點為styles函數定義類型。
import { createThemeFunction } from '../../../theme';
export const styles: createThemeFunction = (theme) => ({
card: {
...theme.mixins.flexColumn,
width:'100%',
height: 'auto',
},
button: {
margin: theme.spacing.unit,
}
});
export type = StyleProps = 'card' | 'button'
現在,我們可以安全的在每個組件中使用他, 并擺脫樣式中CSS屬性的硬編碼類型。
2. Partial and Required
Patial 類型使對象中的所有屬性為可選, 在許多情況下,她可為我們提供幫助, 例如,當使用組件時數據需要在掛載時才能渲染。
// 方法一:
export interface Product {
id:string;
name:string;
price: string;
description: string;
}
export interface ProductInCart {
id: string;
amount:number;
name: string,
label?:string
}
type ModelProps = Partial<{
product: Product,
cartContent: Record<string, ProductInCart>;
}>
// 方法二:
export interface Product {
id?:string;
name?:string;
price?: string;
description?: string;
author?: string;
authorLink?: string;
}
export interface ProductInCart {
id?: string;
amount?:number;
name?: string,
label?:string
}
type ModelProps = {
product: Product,
cartContent: Record<string, ProductInCart>;
}
代碼解析: 方法一和方法二都表示可選參數
或者我們使用Partial定義一些道具作為組件的默認道具:
type Props = OwnProps & WithStyles<WithStyleProps>;
export class SnackbarPure extends React.Component<Props> {
public static defaultProps: Partial<Props> = {
vertical: 'bottom',
horizontal: 'left',
autoDuration: 1000,
}
}
相反,Typescript v2.8中引入的內置類型 Required使所描述對象的所有屬性都必需。
3. Pick and Omit
Pick幫助我們使用已定義的接口,但只從對象中提取您需要的鍵。
Omit它不是Typescript lib.d.ts中預定義的,但很容易用Pick和定義Exclude,它排除了我們不想從接口獲取的屬性。
例如:ProductPhotoProps將包含Product除名稱和描述之外的所有屬性。
// 方法一:
export interface Product {
id:string;
name:string;
price: string;
description: string;
author: string;
authorLink: string;
}
export type PropductPhotoProps = Pick<Product, 'id' | 'author' | 'autoLink' | 'price'>;
// 方法二:
export interface Product {
id:string;
name:string;
price: string;
description: string;
author: string;
authorLink: string;
}
type Omit<T, K extends keyof T> = Pick<T, exclude<keyof T, K>>
export type PropductPhotoProps = Omit<Product, 'name' | 'description'>;
當然,有多種方法可以組合類型并定義它們之間的關系。
如果從一開始就將大東西分解成小塊,可以嘗試用擴展類型,解決排除對象的屬性的問題。
4.Extending type/interface
擴展接口時,結果接口中將提供源接口/類型中描述的所有屬性。讓我們看看如何將小型接口組合成與我們的任務相對應的接口:
export interface ProductAuthor {
author: string,
authorLink: string,
}
export interface ProductBase {
id: string,
price: string,
}
export interface ProductPhotoProps extends ProductAuthor, ProductBase {}
export interface Product extends ProductAuthor, ProductBase {
description: string,
name: string,
}
該方法不太方便,因為您必須預先想象對象的形狀。但是,它既快速又簡單,這使其非常適合用于原型設計或構建簡單的UI,例如將數據呈現到只讀塊中。