gpt4 book ai didi

typescript - 如何从 Typescript 中的类属性(省略方法)派生接口(interface)?

转载 作者:行者123 更新时间:2023-12-02 16:42:22 30 4
gpt4 key购买 nike

我有一些包含所有公共(public)成员的类(本质上是一个结构),我想存储它的数据:

class SomeClass {
public foo: string;
public bar: string;

public getFooBar() {
return this.foo + this.bar;
}
}

作为存储检索的一部分,我想要一个正确定义它的接口(interface),例如:

interface ISomeClassData {
foo: string;
bar: string;
// notice there is no getFooBar()
}

const test: ISomeClassData = magic();
if ("getFooBar" in test === false) {
return "Success. This is an interface, and not a class";
}

做这种事情的一种典型(但不适用)方式如下:

interface ISomeClassData {
foo: string;
bar: string;
}

class SomeClass extends ISomeClassData {
// code omitted
}

在我的场景中,类中的公共(public)属性数量非常大,将某些东西添加到类中而不添加到接口(interface)中真的非常容易。相反,我想做的是从类派生接口(interface)。

是否可以从 Typescript 中的类属性(省略方法)派生接口(interface)?


假想的例子:

type ISomeClassData = JustThePublicProperties<SomeClass>

最佳答案

听起来您想要所有不是函数的键,并且您只想用这些键构建一个对象。

// Get the keys that are not functions. We consider these data.
type ClassDataKeys<T> = {

// Iterate over each property.
[K in keyof T]:

// If the property is a function...
T[K] extends (...args: any[]) => any

// Functions are not allowed, use never to exclude it.
? never

// Not a function, it is data, set the value of this property to its own key.
: K

// Get the union of all values (which are now the keys that have not been set to `never`)
}[keyof T]

// Pick just the keys from the class that are ClassDataKeys.
type ClassData<T> = Pick<T, ClassDataKeys<T>>

// Works!
const test1: ClassData<SomeClass> = {
foo: 'asd',
bar: 'asd',
}

Playground

这是一个两步过程。首先是使用映射类型和条件来测试每个属性是否是一个函数。然后收集那些不是函数的属性名。最后,只选择被视为类数据的属性名称。

关于typescript - 如何从 Typescript 中的类属性(省略方法)派生接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61375506/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com