Issue
const labelTypeMap = useMemo<Record<'between' | 'inner', string>>(
() => ({
between: formatMessage({ id: 'addGroup' }),
inner: '+',
aaa: 123, // no error here
}),
[]
);
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.
Solution
Here's a simplified version that still demonstrates the issue:
const labelTypeMap: Record<"between" | "inner", string> = (() => ({
between: "xxx",
inner: "+",
aaa: 123,
}))();
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
};
Now it will complain 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;
}, []);
This also works:
const labelTypeMap = useMemo(
(): Record<"between" | "inner", string> => ({
between: "xxx",
inner: "+",
aaa: 123, // Error as expected
}),
[],
);
Answered By - cyco130
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.