TypeScript 内置类型记录

47 阅读1分钟

TypeScript 内置了一些类型,包括 ES5,ES6 语法 API 的类型声明,很多地方看起来很有意思。我也不知道学习 TypeScript 从哪里入手,索性看着写声明文件学习一下,遇到有趣的就记录一下。因此未有定序,不似别人脉络清晰,偶有所得,翻用自喜。

is 使用

Array 的 every 方法,类型声明很有意思:

interface ReadonlyArray<T> {
  ...
   /**
     * Determines whether all the members of an array satisfy the specified test.
     * @param predicate A function that accepts up to three arguments. The every method calls
     * the predicate function for each element in the array until the predicate returns a value
     * which is coercible to the Boolean value false, or until the end of the array.
     * @param thisArg An object to which the this keyword can refer in the predicate function.
     * If thisArg is omitted, undefined is used as the this value.
     */
    every<S extends T>(predicate: (value: T, index: number, array: readonly T[]) => value is S, thisArg?: any): this is readonly S[];
    /**
     * Determines whether all the members of an array satisfy the specified test.
     * @param predicate A function that accepts up to three arguments. The every method calls
     * the predicate function for each element in the array until the predicate returns a value
     * which is coercible to the Boolean value false, or until the end of the array.
     * @param thisArg An object to which the this keyword can refer in the predicate function.
     * If thisArg is omitted, undefined is used as the this value.
     */
    every(predicate: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any): boolean;
}

第二个类型声明很简单,就是 every 返回一个 boolean 判断 every 是否全部通过测试。第一个类型声明重点在于 is,is 在 TypeScript 中叫做类型谓词,简单理解就是可以收缩类型。这个类型声明的意思就是,假设 predicate 可以将数据类型收缩到 S,可以认为通过 every