[Typescript] Type Queries (keyof & typeof)

时间:2022-08-10
本文章向大家介绍[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.

原文地址:https://www.cnblogs.com/Answer1215/p/16573660.html