• [Typescript] Type Queries (keyof & typeof)


    keyof

    The keyof type query allows us to obtain type representing all property keys on a given interface.

    key can be string, number or Symbol.

    So what if you only want get string type key?

    type DatePropertyNames = keyof Date

    Not all keys are strings, so we can separate out those keys that are symbols and those that are strings using the intersection operator (&).

    type DatePropertyNames = keyof Date
    
    type DateStringPropertyNames = DatePropertyNames & string
    //    "toString" | "toDateString" | "toTimeString" | "toLocaleString" | "toLocaleDateString" | "toLocaleTimeString" | "valueOf" | "getTime" | "getFullYear" | "getUTCFullYear" | ... 33 more ... | "getVarDate"
    type DateSymbolPropertyNames = DatePropertyNames & symbol
    //    type DateSymbolPropertyNames = typeof Symbol.toPrimitive

    typeof

    The typeof type query allows you to extract a type from a value. An example is shown below

    async function main() {
      const apiResponse = await Promise.all([
        fetch("https://example.com"),
        Promise.resolve("Titanium White"),
      ])
     
      type ApiResponseType = typeof apiResponse
      //  type ApiResponseType = [Response, string]
    }

    The following code:

    class Fruit {
      constructor(
        public readonly name: string,
        public readonly mass: number,
        public readonly color: string
      ) {}
     
      static createBanana() {
        return new Fruit("banana", 108, "yellow")
      }
    }
    
    const MyFruit = Fruit // const MyFruit: typeof Fruit
    const fruit = new Fruit("banana", 10, "yellow"); // const fruit: Fruit
    const banana = Fruit.createBanana(); // const banana: Fruit

    If you just use:

    const MyFruit = Fruit

    It point to constructor, and static methods. Anyhow, in javascript, Class is just a function.

  • 相关阅读:
    在HTML网页中嵌入脚本的方式
    纪念品分组(贪心、排序)
    合并果子(STL优先队列)
    铺地毯(取最上层的地毯)
    多项式方程的输出
    BF算法(蛮力匹配)
    数位的处理
    两个数的差
    多项式计算器
    随机数生成器java实现
  • 原文地址:https://www.cnblogs.com/Answer1215/p/16573660.html
Copyright © 2020-2023  润新知