我有两个对象,它们不应该有任何普通的叶子:
const translated = {
a: {
b: {
c: "Hello",
d: "World"
}
}
};
const toTranslate = {
a: {
b: {
d: "Everybody"
}
}
};
上面的代码应该会产生一个错误:两个对象中都有‘a.b.d’.
我可以很容易地编写单元测试来判断这一点,但我试图生成一个很好的编译时错误消息.
我的try 是:
type Leaves<T> = T extends object ? { [K in keyof T]:
`${Exclude<K, symbol>}${Leaves<T[K]> extends never ? "" : `.${Leaves<T[K]>}`}`
}[keyof T] : never
type TranslatedLeaves = Leaves<typeof translated>
type ToTranslateLeaves = Leaves<typeof toTranslate>
type Overlap = TranslatedLeaves & ToTranslateLeaves
type ErrorIfOverlapping<T extends never = Overlap> = void;
请参见:
- Typescript: deep keyof of a nested object个
- Typescript: check for intersections between union types, ensure all members are unique个
不幸的是,这只给了我Type 'string' does not satisfy the constraint 'never'.
是否可以用所有公共的叶子生成一个错误消息?