useMemo 返回类型错误,但是tsc 不会显示错误? [英] useMemo return type is wrong, but tsc will not show error?

查看:34
本文介绍了useMemo 返回类型错误,但是tsc 不会显示错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

const labelTypeMap = useMemo<Record<'between' | 'inner', string>>(
  () => ({
    between: formatMessage({ id: 'addGroup' }),
    inner: '+',
    aaa: 123, // no error here
  }),
  []
);

作为代码,在aaa上没有错误,即使它与useMemo的返回类型不匹配.任何帮助将不胜感激.

As the code, there's no error on aaa, even it doesn't match the return type of useMemo. Any help will be much appreciated.

推荐答案

这是一个仍然可以演示问题的简化版本:

Here's a simplified version that still demonstrates the issue:

const labelTypeMap: Record<"between" | "inner", string> = (() => ({
    between: "xxx",
    inner: "+",
    aaa: 123,
}))();

问题是 Typescript 通常允许对象具有额外的属性.毕竟,具有额外属性的对象 与基本类型兼容(在面向对象的意义上).仅当您使用 Object.keys 等动态内省功能时,才会出现意外.

The issue is that Typescript, in general, allows extra properties on objects. After all, an object with extra properties is compatible (in an object-oriented sense) with the base type. Surprises only happen when you use dynamic introspection features like Object.keys and similar.

这种灵活性的唯一例外是当您尝试直接分配对象文字时:

The only exception to this flexibility is when you try to assign an object literal directly:

const labelTypeMap: Record<"between" | "inner", string> = {
    between: "xxx",
    inner: "+",
    aaa: 123, // Error as expected
};

现在它会按预期抱怨.

因此,您的问题的一种可能解决方案是:

So one possible solution to your problem is this:

const labelTypeMap = useMemo(() => {
    const result: Record<"between" | "inner", string> = {
        between: "xxx",
        inner: "+",
        aaa: 123, // Error as expected
    };

    return result;
}, []);

这也有效:

const labelTypeMap = useMemo(
    (): Record<"between" | "inner", string> => ({
        between: "xxx",
        inner: "+",
        aaa: 123, // Error as expected
    }),
    [],
);

这篇关于useMemo 返回类型错误,但是tsc 不会显示错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆