typescript - TS 标记字符串作为对象的键
问题描述
想象一下,我有带有字符串标识符的类 Foo 。
class Foo {
id = '123' as FooId;
}
我尝试使用品牌 enum确保它的静态类型。
enum FooIdBranding {}
type FooId = string & FooIdBranding;
所以现在,我的目标是特定对象,键在哪里,FooId
值在哪里Foo
。
type fooCache = { [key: FooId]: Foo };
不幸的是,它不起作用:
TS1023:索引签名参数类型必须是“字符串”或“数字”
我想,记录是我的解决方案,但也不起作用。
type FooCache = Record<FooId, Foo>;
({} as FooCache)['123' as FooId] = new Foo();
TS 7017:元素隐式具有“任何”类型,因为类型
Record<FooId, Foo>
没有索引签名
TypeScript 中是否有解决此问题的正确方法?
解决方案
“符号和模板字符串模式索引签名”已添加到 TypeScript 4.4中,因此现在可以这样做。
type FooId = string & {brand: 'FooId'};
const id1 = '1' as FooId
const id2 = '2' as FooId
class Foo {
constructor(public id: FooId) {}
}
type fooCache = { [key: FooId]: Foo };
const foo: fooCache = {
// Type '{ key: Foo; }' is not assignable to type 'fooCache'.
// Object literal may only specify known properties, and 'key' does not exist in type 'fooCache'.(2322)
// (property) key: Foo
key: new Foo(id1)
}
// All good
const bar: fooCache = {
[id1]: new Foo(id1)
}
推荐阅读
- python - 如何在 Python 3 中使用组合的格式化字符串文字和三引号来修复代码?
- python-3.x - 将列表拆分为随机排序的子列表
- python - 当仅返回单个值时,如何在 for 循环中使用追加的多值列表?
- html - 将css文件链接到html文件
- unit-testing - Flutter:如何测试 Widgets State 类中的方法?
- c++ - 什么时候调用handle_read 和handle_write?
- spring-boot - 测试容器和 Spring Boot 1.5
- javascript - 当我将表单移动到其他文件时,此 handleSubmit() 不起作用
- json - 经典asp json ASP-Xtreme 遍历json对象
- matlab - 如何修复 FOR 循环中的“下标分配维度不匹配”错误