[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 @   Zhentiw  阅读(21)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2020-08-10 [CSS] Create Complex Shapes with CSS Clip Path and Border Radiusc (border-radius & clip-path)
2020-08-10 [CSS] Create a Responsive Unit and Container
2020-08-10 [Javascript] Number, toLocaleString() & Intl
2020-08-10 [XState] Actor Model
2018-08-10 [Algorithms] Determine if a string is a palindrome
2018-08-10 [Algorithm] Determine if two strings are an anagram
2017-08-10 [D3] Build a Column Chart with D3 v4
点击右上角即可分享
微信分享提示