[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.

 

posted @ 2022-08-10 19:30  Zhentiw  阅读(20)  评论(0编辑  收藏  举报