如何正确地使用Typescript将不可变映射转换为严格类型



如何将以下内容从js转换为Typescript:

Immutable.Map({
item1: null,
item2: "hello",
item3: Immutable.Map({
item4: 2,
item5: true
})
});

我不熟悉immutable.js框架,但我建议使用标准的JavaScript映射。Typescript的类型为ReadonlyMap,它基本上会从映射对象中删除所有setter。对象本身并不是真正可输入的(也就是说,没有运行时错误(,但如果您尝试添加/删除/更新值,typescript编译器会抱怨。

const myMap: ReadonlyMap<string, string> = new Map([
['item1', 'foo'],
['item2', 'bar']
]);
console.log(myMap.get('item1')); // will log foo
myMap.set('item1', 'foobar'); // Property set does not exist on type readonly map

有点偏离主题,但我建议重新思考您的地图结构。当然string | null是好的。但string | null | ReadonlyMap<string, number | boolean>(对我来说(听起来确实像是一个编织的地图

此外,如果您想阅读,这里还有地图文档。

您可以执行以下操作:

type Immutable<T> = {
readonly [K in keyof T]: Immutable<T[K]>;
};
// Then you could write your interface 
interface Person {
name: string;
lastName: string;
address: {
street: string;
zipCode: number;
}
}
const person: Immutable<Person> = {
name: 'joe',
lastName: 'smith',
address: {
street: 'smith street',
zipCode: 55555
}
}
// Then when you try to mutate, typescript should throw an error that it is a readonly property
person.name = 'alice';
person.address.street = 'ano'

这篇文章的作者在这里链接:https://www.sitepoint.com/compile-time-immutability-in-typescript/

最新更新