TS branded string as key of the object

◇◆丶佛笑我妖孽 提交于 2020-06-27 18:06:09

问题


Imagine, that I have class Foo with string identifier.

class Foo {
    id = '123' as FooId;
}

I try to ensure static typing of it using a brand enum.

enum FooIdBranding {}
type FooId = string & FooIdBranding;

So now, my goal is specific object, where the key is FooId and the value is Foo.

type fooCache = { [key: FooId]: Foo };

Unfortunately, it doesn't work:

TS1023: An index signature parameter type must be 'string' or 'number'

I thought, that the Record is my solution, but is doesn't work too.

type FooCache = Record<FooId, Foo>;

({} as FooCache)['123' as FooId] = new Foo();

TS 7017: Element implicitly has an 'any' type because type Record<FooId, Foo> has no index signature

Is there a correct way in TypeScript to resolve this problem?

来源:https://stackoverflow.com/questions/56020400/ts-branded-string-as-key-of-the-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!