高级TypeScript类型

本文将提供使用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,例如将数据呈现到只读块中。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,830评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,992评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,875评论 0 331
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,837评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,734评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,091评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,550评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,217评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,368评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,298评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,350评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,027评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,623评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,706评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,940评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,349评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,936评论 2 341

推荐阅读更多精彩内容