具有与通用属性相同的Typescript类?

时间:2019-09-30 15:32:54

标签: typescript

我想创建一个具有通用参数且其属性与通用参数相同的类:

// Does not work
/* interface Interf<TProps> {
    [P in keyof TProps] : TProps[P];
} */

class Test<TProps> /* implements Interf<TProps> */ {
    // Does not work either
    //[P in keyof TProps] : TProps[P];

    constructor(props: TProps) {
        for (let name in props) {
            (this as any)[name] = props[name];
        }
    }

    // Some methods...
}

let test = new Test({foo: "bar"});
// Error : Property 'foo' does not exist on type 'Test<{ foo: string; }>'.
console.log(test.foo);

关于如何获取打字稿以允许访问属性foo(仅限属性foo)的任何想法吗?

0 个答案:

没有答案