问题
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