const labelTypeMap = useMemo<Record<'between' | 'inner', string>>(
() => ({
between: formatMessage({ id: 'addGroup' }),
inner: '+',
aaa: 123, // no error here
}),
[]
);
作为代码,aaa
没有错误,即使它不匹配useMemo的返回类型。
任何帮助将不胜感激。
最佳答案
这是一个简化的版本,它仍然演示了这个问题:
const labelTypeMap: Record<"between" | "inner", string> = (() => ({
between: "xxx",
inner: "+",
aaa: 123,
}))();
问题是 Typescript 通常允许对象有额外的属性。毕竟,具有额外属性的对象是与基本类型兼容(在面向对象的意义上)。只有当您使用 Object.keys
等动态内省(introspection)功能时才会出现意外。
这种灵 active 的唯一异常(exception)是当您尝试直接分配对象文字时:
const labelTypeMap: Record<"between" | "inner", string> = {
between: "xxx",
inner: "+",
aaa: 123, // Error as expected
};
现在它会像预期的那样提示。
因此,您的问题的一种可能解决方案是:
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
}),
[],
);
关于reactjs - useMemo 返回类型错误,但 tsc 不会显示错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66793710/