barOrBaz
value should be restricted to foo
constant keys:
const foo = {
BAR: 'BAR',
BAZ: 'BAZ'
};
let barOrBaz: keyof typeof foo; // type: "BAR" | "BAZ"
const BAR = 'BAR';
barOrBaz = BAR; // ok
barOrBaz = 'BAZ'; // ok
barOrBaz = foo.BAR; // Type 'string' is not assignable to type '"BAR" | "BAZ"
The problem is that when barOrBaz
is assigned to foo.BAR
(which is the usual way how foo
is used), it triggers an error:
Type 'string' is not assignable to type '"BAR" | "BAZ"
Why is foo.BAR
interpreted as string
and not "BAR"
string type?
How can this be fixed? Are there other ways to implement this?