持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第21天,点击查看活动详情
#开发技巧
1. 对于可选参数用!来规避undefined,null的情况
interface ButtonProps {
title: string;
type?: 'primary' | 'danger';
onLabelClick?: (name: string) => void
}
const Button = (props:ButtonProps) => {
//实际开发中都是结构出来取值的,解构过程中实际已经给了默认值
props!.type
// 同样也可以
const {onLabelClick} = props
// 这种情况还是比较常用。相当于我们的onLabelClick && onLabelClick()
onLabelClick!()
}
和es6 的?.很像,主要区别是一个在编译时校验,
一个是在运行时校验
2.尽量使用typeof来定义类型,减少不必要的导出
import React from "react"
import Child from "./child"
type ParentProps = React.ComponentProps<typeof Child> & {
age: number
}
const Parent = FC(props: ParentProps) => {
return (
<div>
<Child/>
</div>
)
}
//child.tsx
type ChildProps = {
name: string
}
const Child = FC(props: ChildProps) => {
return (
<div>
<Child/>
</div>
)
}
如下所示,props: React.ComponentProps<"button">获取button组件的所有props
所以click方法也可以巧妙的现货区所有props 然后取onClick就得到类型定义`onClickButton:React.ComponentProps<"button">["onClick"]
``
3.FC 即functionComponent 会自动帮我们加上children的属性
如果自己定义children则为 ReactNode[] | ReactNode
一般推荐使用FC
FC(props: PropsInterface) 实际相当于
PropsInterface & {
children: React.ReactNode
propTypes?: WeakValidationMap<P>;
contextTypes?: ValidationMap<any>;
defaultProps?: Partial<P>;
displayName?: string;
}
4.接口方法定义
// function get(url: string, opts: Options): Promise<Response> { /* ... */ }
type HTTPFunction = (url: string, opts: Options) => Promise<Response>;
const get: HTTPFunction = (url, opts) => { /* ... */ };
5.利用三元运算符根据泛型限制值
很巧妙的限制了当T为string的时候值为1,否则则值为2
type B<T> = T extends string ? '1' : '2'
6.namespace·命名空间的主要作用是不需要引入,直接使用
declare namespace MarketApi {
interface Product {
productName: string;
productID: string;
date: date;
id: number;
}
}
const data:MarketApi.Product = result.data
7.定义action的类型
type ActionType<M extends Model | string> = M extends Model ? `${M['namespace']}/${(keyof M['effects'] | keyof M['reducers']) & string}` : string
declare type dispatch = ({action: ActionType<M>, payload?: any}) => void
8.枚举
enum Status { START = 0, PENDING, END }
枚举后面的所有值自动加1和其他语言枚举一致。同样枚举和其他语言保持一致,也可以给每个枚举值赋值字符串
enum Status {
START = 'status',
PENDING = 'pending',
END = 'end'
}
使用,根据不同的状态加载不同的样式。可以下面这样来处理
const className = `order-container-${status}`
9.Record<K, V>,能够快速的为object创建统一的key和value类型。
const marketType: Record<string, string> = {
name: '222',
age: 2 // 必须为string
}