简体   繁体   English

有没有一种类型级别的方法可以从类中提取具有默认值的属性?

[英]Is there a type-level way to extract properties that have default from a class?

I want to extract the key names of properties in a class that have default values. 我想提取具有默认值的类中的属性的键名。 Is this information available to the type system? 该信息可用于类型系统吗?

class Foo {
  hasDefault: boolean = true
  alsoHasDefault: number = 42
  noDefault: boolean
}

// How can this be implemented?
type DefaultPropertyNames<T> = ... 

// Example output:
type FooDefaults = DefaultPropertyNames<Foo> // -> 'hasDefault' | 'alsoHasDefault'

I think what you mean by "no default value" is that the value can be undefined. 我认为“无默认值”的意思是该值可以不确定。 Currently, your code throws a type error because noDefault does not contain undefined in its type definition. 当前,您的代码引发类型错误,因为noDefault在其类型定义中不包含undefined。

So let me reframe the question: 因此,让我重新构想这个问题:

How do I find all of the keys in a class that are potentially undefined? 如何找到类中所有可能未定义的键?

Something like this works: 像这样的作品:

type DefaultPropertyNames<T> = Exclude<{
    [K in keyof T]: {key: K, value: T[K] extends T[K] & {} ? true : false}
}[keyof T], {value: false}>["key"]

playground 操场

To explain a little bit: 解释一下:

  • T[K] & {} removes undefined from a type. T[K] & {}从类型中删除undefined

  • T[K] extends T[K] & {} tells you if undefined is in the union type T[K] extends T[K] & {}告诉您undefined是否在并集类型中

  • {[K in keyof T]: ... }[keyof T] creates a union type from each property key {[K in keyof T]: ... }[keyof T]从每个属性键创建一个联合类型

  • Exclude lets you remove items from the union type. Exclude使您可以从联合类型中删除项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM