gpt4 book ai didi

typescript :接口(interface)字段上的元数据

转载 作者:搜寻专家 更新时间:2023-10-30 21:36:31 26 4
gpt4 key购买 nike

我正在尝试创建一个框架,允许我在界面字段上使用元数据。像这样:

function path(path) {}

interface ITwoProps {
@path('some/path') stringProp: string;
@path('different/path') boolProp: boolean;
}

class Impl1 implements ITwoProps {
get stringProp() {
return 'abc';
}
get boolProp() {
return !!'abc';
}
}

playground link

不幸的是,这甚至无法编译。错误消息有点模糊,但想法是装饰器在接口(interface)上被隐式禁用。它确实有意义,因为接口(interface)不会将其转换为转译代码,因此不会有转译代码来附加装饰器。

我还尝试了另一种方法,在这种方法中,我将使用类似模式的对象定义元和接口(interface),并从中提取接口(interface):

const Schema = {
boolProp: {
type: Boolean,
path: 'some/path'
},
stringProp: {
type: String,
path: 'different/path'
},
};

type PropertyDef<T> = {
type: (...args: any[]) => T,
path?: string;
};

type ExtractType<X> = X extends PropertyDef<infer T> ? T : never;

type ObjectInterface<T extends {[key: string]: PropertyDef}> = {
[P in keyof T]: ExtractType<T[P]>;
}

class Impl2 implements ObjectInterface<typeof Schema> {
get foo() {
return !!'abc';
}
}

playground link

这也不起作用,因为 PropertyDef 需要一个参数。此外,这可能比仅支持一个接口(interface)更难支持更复杂的情况。

问题是 - 如何将接口(interface)与 typescript 中的元结合起来?虽然我最感兴趣的是使第一种方法起作用,但我对不同的建议持开放态度,甚至可能对使用 Compiler API 的变压器也持开放态度。 .

最佳答案

接口(interface)装饰器的方法没有语言支持,并且作为@Daniel-Rosenwasser 暗示它可能不会得到支持。另一种方法是使用抽象类,您可以使用 implements使用类只保留类的接口(interface)而不是代码,尽管它可能有点困惑。

不过,我还是建议您再看看第二种方法。它只需要一个额外的 <any>让它工作。由于您可以完全控制元数据系统,因此它实际上可能会证明具有更大的灵 active 。我尝试使用与此类似的系统创建更复杂的类型,并且可以完成。在您的情况下,这会起作用:

const Schema = {
boolProp: {
type: Boolean,
path: 'some/path'
},
stringProp: {
type: String,
path: 'different/path'
},
};

type PropertyDef<T> = {
type: (...args: any[]) => T,
path?: string;
};

type ExtractType<X> = X extends PropertyDef<infer T> ? T : never;

type ObjectInterface<T extends { [key: string]: PropertyDef<any> }> = {
[P in keyof T]: ExtractType<T[P]>;
}

class Impl2 implements ObjectInterface<typeof Schema> {
get boolProp() {
return !!'abc';
}
get stringProp() {
return '';
}
}

关于 typescript :接口(interface)字段上的元数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50802291/

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