I've encountered a peculiar situation while using branded strings as keys in an object with TypeScript. The compiler fails to flag what I believe are clear type errors in certain scenarios.
Here is a simplified version of the issue:
type SpecialKey = string & {__SpecialKey: true};
type SpecialKeysToStrings = {
[key: SpecialKey]: string;
}
// This works
const obj1: SpecialKeysToStrings = {
['myKey' as SpecialKey]: "string",
};
// Compiler catches this problem as the value is not a string
const obj2: SpecialKeysToStrings = {
['myKey' as SpecialKey]: 100,
};
// Compiler fails to catch this problem as the value is not a string
const obj3: SpecialKeysToStrings = {
...{},
['myKey' as SpecialKey]: 100,
}
Interestingly, in the case of obj3
, the presence of an object spread before ['myKey' as SpecialKey]: 100
seems to confuse the compiler, causing it to overlook the type error.
This behavior appears to occur only when:
- a branded type is used as a key, and
- an object spread is included.
Removing either of these elements results in TypeScript behaving correctly. Am I overlooking something? Is this the expected behavior? Have the branded types led me beyond TypeScript's capability to handle correctly? Could this be a bug in the compiler?