React FunctionComponent 源码的 TS知识点

44 min read
interface FunctionComponent<P = {}> {
        (props: P, context?: any): ReactElement<any, any> | null;
        propTypes?: WeakValidationMap<P> | undefined;
        contextTypes?: ValidationMap<any> | undefined;
        defaultProps?: Partial<P> | undefined;
        displayName?: string | undefined;
}

函数接口定义

(props: P, context?: any): ReactElement<any, any> | null;

本质上函数也是一个对象,也可以为该函数增加其它属性

泛型默认值

<P = {}>

处理传入类型集合为可选 optional

Partial<P>
  
  
/**
 * Make all properties in T optional
 */
type Partial<T> = {
    [P in keyof T]?: T[P];
};

keyof

返回从指定类型对象的key的字面量

interface CountryResp {
  name:
  string
  area:
  number;
  population: number
}

type Keys = keyof CountryResp

WeakValidationMap 泛型类型的可编程化

type WeakValidationMap<T> = {
    [K in keyof T]?: null extends T[K]
    ? Validator<T[K] | null | undefined>
    : undefined extends T[K]
    ? Validator<T[K] | null | undefined>
    : Validator<T[K]>
};

// 画个区间解构一下

type WeakValidationMap<T> = {   //T 实际传往后 props类型  T[K] 表示props对象key的类型
    [K in keyof T]?: 
  +++ null extends T[K]   // `null extends T[K]` null 是否是T[K]的子类型 
    ? Validator<T[K] | null | undefined>
    : undefined extends T[K]
    ? Validator<T[K] | null | undefined>  // 连续的三元表达式
    : Validator<T[K]> +++
};