带有只读键的打字稿字典

Typescript dictionary with readonly keys

是否可以在带有只读键的打字稿中声明字典 class?

代码:

class Dictionary {
    readonly[key: string]: string;

    constructor(props: Dictionary) {
        for (const key in props) {
            this[key] = props[key];
        }
    }
}

通常在构造函数中允许设置只读属性的值,但编译器在这里抱怨“'Dictionary' 类型的索引签名只允许读取”。

我不确定这是否是设计使然,the docs 对此感到困惑:

A property or index signature can now be declared with the readonly modifier is considered read-only.

但是:

Read-only properties may have initializers and may be assigned to in constructors within the same class declaration, but otherwise assignments to read-only properties are disallowed

因此,虽然属性和索引签名都可以是只读的,但也许只能在构造函数中分配属性。
不清楚的可以开个issue看看

但是您可以使用 Object.assign,它不会以编译错误结束,它也会清除代码:

class Dictionary {
    readonly[key: string]: string;

    constructor(props: Dictionary) {
        Object.assign(this, props);
    }
}

let d1 = new Dictionary({ key1: "one", key2: "two" });
console.log(d1); // Dictionary {key1: "one", key2: "two"}

let d2 = new Dictionary(d1);
console.log(d1); // Dictionary {key1: "one", key2: "two"}

(code in playground)


编辑

使用 Object.assign 比你的 for/in 循环更好,下面是一个例子:

class A {
    [key: string]: any;

    constructor() {
        this["k1"] = "v1";
        this["k2"] = "v2";
    }

    method() {}
}

let a = new A();
let a1 = Object.assign({}, a);
console.log(a1); // { k1: "v1", k2: "v2" }

let a2 = {};
for (const key in a) {
    a2[key] = a[key];
}
console.log(a2); // { k1: "v1", k2: "v2", method: () }

(code in playground)

如您所见,使用 for/in 循环还将迭代原型属性,这可能不是您想要的。
Object.assign没有这个问题。

另一种选择是使用 Object.keys:

let a3 = {};
Object.keys(a).forEach(key => a3[key] = a[key]);
console.log(a3); // { k1: "v1", k2: "v2" }