最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

TypeScript not catching potential undefined properties in union type with Record<string, never> - Stack Overflow

programmeradmin5浏览0评论

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

  1. 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.

  2. 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?

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论