当我直接调用函数时,这不是问题,但在这种情况下,通过另一个函数(如下面的示例)在内部调用时,Typescript无法捕获错误:
const updatePerson = ({
name,
onCurrentPerson,
}: {
name: Person['name'];
onCurrentPerson: (personValue: Person) => Person;
}) => {
const updatedPeople = people.map((currentPerson) => {
if (currentPerson.name !== name) return currentPerson;
return onCurrentPerson(currentPerson);
});
return updatedPeople
};
请参见Typescript练习场上的以下代码
interface Person {
name: string
age: number
}
const people: Person[] = [{name: "John", age: 20}]
const updatePerson = ({
name,
onCurrentPerson,
}: {
name: Person['name'];
onCurrentPerson: (personValue: Person) => Person;
}) => {
const updatedPeople = people.map((currentPerson) => {
if (currentPerson.name !== name) return currentPerson;
return onCurrentPerson(currentPerson);
});
return updatedPeople
};
updatePerson({
name: "John",
onCurrentPerson: (currentPerson) => {
const person: Person = {
...currentPerson,
age: 22,
language: "English" // <-- Throws an error
};
return person;
},
});
updatePerson({
name: "John",
onCurrentPerson: (currentPerson) => ({
...currentPerson,
age: 22,
language: "English" // <-- Does not throw an error
}),
});
正如您所看到的,我当前的解决方案要求我在返回之前检查值:
onCurrentPerson: (currentPerson) => {
const person: Person = {
...currentPerson,
age: 22,
language: "English" // <-- Throws an error
};
return person;
},
我想了解为什么在我像下面的示例那样调用此错误时不显示它:
updatePerson({
name: "John",
onCurrentPerson: (currentPerson) => ({
...currentPerson,
age: 22,
language: "English" // <-- Does not throw an error
}),
});
我遗漏了什么?如何在返回值之前不必检查类型的情况下增强类型?
1条答案
按热度按时间lnlaulya1#
这是由于过多的属性检查造成的。
您需要的修复程序将随TS 4.9一起提供:
satifies