I'm encountering what seems to be unexpected behavior in TypeScript when working with a union type that includes Record<string, never>
(empty object). TypeScript isn't catching potential undefined properties access, which could lead to runtime errors.
Here's a minimal example:
type CatData = {
name: string;
breed: string;
age: number;
};
type MaybeCatData = Record<string, never> | CatData;
// TypeScript doesn't complain about this, but it should!
function processCat(obj: MaybeCatData): CatData {
return {
name: obj.name,
breed: obj.breed,
age: obj.age
};
}
/**
* Returns: {
* "name": undefined,
* "breed": undefined,
* "age": undefined
* }
*/
console.log(processCat({}));
The Problem
When I define a union type
MaybeCatData = Record<string, never> | CatData
, I expect TypeScript to force me to check whether the properties exist before accessing them, since one possibility is an empty object.However, TypeScript allows direct access to these properties without any type checking, even though accessing properties on an empty object will return undefined.
Question
Is there a better way to type this scenario to force proper type checking?