【问题标题】:Allow arbitrary properties in class Typescript types允许 Typescript 类型中的任意属性
【发布时间】:2019-07-11 05:19:28
【问题描述】:

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

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

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

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

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

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

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

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

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

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

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

非常感谢!

【问题讨论】:

    标签: typescript typescript-typings


    【解决方案1】:

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

    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
    

    【讨论】:

    • 哇!那太棒了!非常感谢!但是你为什么要把“_MyClass as any”呢?
    • @AlexanderCerutti 因为从技术上讲,它不会返回 MyClass 声明的类型。所以我们用锤子让它合身?
    • 哦,好吧...我现在明白了。我试图删除它并看到。打字稿有时很奇怪。再次,非常感谢!
    猜你喜欢
    • 2020-01-04
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    • 2020-05-11
    • 2016-02-23
    • 2021-09-09
    • 1970-01-01
    相关资源
    最近更新 更多