TypeScript知识

176 阅读1分钟
  • 可选属性的替代方案
        // 1.增加可选参数,使得c属性可有可无
      interface O {
        a: string;
        b: number;
        c?: number;
      }
      // 2.可允许添加任意数量的参数
      interface O {
        a: string;
        b: number;
        [propName: string]: any;
      }
    
  • interface与type差别
    • type 可以声明基本类型别名,联合类型,元组等类型
    // 基本类型别名
    type Name = string
    
    // 联合类型
    interface Dog {
       wong();
    }
    interface Cat {
       miao();
    }
    
    type Pet = Dog | Cat
    
    // 具体定义数组每个位置的类型
    type PetList = [Dog, Pet]
    
    • type 语句中还可以使用 typeof 获取实例的 类型进行赋值
       // 当你想获取一个变量的类型时,使用 typeof
     let div = document.createElement('div');
     type B = typeof div
    
  • 骚操作
  type StringOrNumber = string | number;  
  type Text = string | { text: string };  
  type NameLookup = Dictionary<string, Person>;  
  type Callback<T> = (data: T) => void;  
  type Pair<T> = [T, T];  
  type Coordinates = Pair<number>;  
  type Tree<T> = T | { left: Tree<T>, right: Tree<T> };
  • typeinterface在React中.d.ts的应用
type FC<P = {}> = FunctionComponent<P>;

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

首先,您可以看到 FC 只是 FunctionComponent 接口的别名。 它们都是泛型的,可以很容易地通过类型名称后面的角括号来识别。 在尖括号中有 P = {}.。 这意味着,您可以将类型作为参数传递,在新类型中,传递的类型将默认使用空对象 {} 的名称 P 。