允许类 Typescript 类型中的任意属性 [英] Allow arbitrary properties in class Typescript types

查看:36
本文介绍了允许类 Typescript 类型中的任意属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Typescript 中创建了一个泛型类来扩展从构造函数中传递的对象开始(通过代理,它将在构造函数中返回).

I've created a generic class in Typescript to extend objects starting from one passed in the constructor (through a Proxy, which will be returned in the constructor).

class MyClass<T> {
    private _a: 5;
    constructor(source: T) {
        ...
        return new Proxy(Object.assign(this, source), { ... });
    }
}

如果我想实例化MyClass,我会这样做:

If I want to instance MyClass, I'll do:

interface DeepObject {
    a: number,
    b: {
         c: number,
         d: { ... }
    }
}

const x = new MyClass<DeepObject>({
    a: 1,
    b: {
        c: 2,
        d: { ... }
    }
});

因此,作为结果,我将得到 x 作为具有内部DeepObject"属性的类,例如 abbd.但是,如果我尝试访问 x.b.d,它显然无法识别新属性,因为它们在当前状态下在运行时被推入内部.有没有办法使用 MyClass 的 T 参数作为类返回类型,知道我正在返回一个编辑过的this"(MyClass + new props)?我试图将它设置为构造函数,但打字稿不允许我,比如

So, as result, I will get x as a class that has inside "DeepObject" properties, like a, b, b.d. But if I try to access to x.b.d, it will obliviously not recognize the new properties as they get pushed inside in runtime at the current state. Is there a way to use MyClass's T parameter as a class return type, knowing that I'm returning an edited "this" (MyClass + new props)? I tried to set it to the constructor but typescript doesn't let me, like

    constructor(source: T): ThisType<MyClass<T>> & T { ... }
    constructor(source: T): MyClass<T> & T { ... }

此外,在多行中使用//@ts-ignore(如

Moreover, using //@ts-ignore in multiple lines (like

//@ts-ignore
x.b.c = 5;
//@ts-ignore
x.b.d.f = 9;

),恕我直言,这是对打字稿功能的误用.

), is a misusage of typescript features, IMHO.

同样是把[key: string]: any放在类里面,在属性上面或者下面.

The same is to put [key: string]: any inside the class, above or below the properties.

非常感谢!

推荐答案

不能直接对构造函数的返回类型收费.但是,您可以使用与 Proxy 相同的方法,并为构造函数单独声明,该声明在返回中使用泛型类型参数

You can't directly charge the return type of the constructor. You can however use the same approach as Proxy usses and have a separate declaration for the constructor which does use the generic type parameter in the return

class _MyClass<T> {
    private _a: 5;
    constructor(source: T) {

        return new Proxy(Object.assign(this, source), { ... });
    }
}

interface DeepObject {
    a: number,
    b: {
        c: number,
        d: {  }
    }
}
const MyClass : {
    new<T> (s:T) : _MyClass<T> & T
} = _MyClass as any
const x = new MyClass<DeepObject>({
    a: 1,
    b: {
        c: 2,
        d: {  }
    }
});

x.b.c

这篇关于允许类 Typescript 类型中的任意属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆