简而言之,我需要一个返回either类型"Person"或类型"PersonWithSurname"的函数.这与条件类型一起工作得很好.然而,我正在努力在没有错误的情况下构建结果.
interface Person {
name: string;
}
type PersonWithSurname = Person & {
surname : string
};
type PersonNameConditional<T> = T extends true
? PersonWithSurname
: Person;
function getPerson<T extends boolean>(returnSurname: withSurname
): PersonNameConditional<T> {
if (returnSurname) {
return { name: "John", surname: "Wic-k" } as PersonNameConditional<withSurname>
} else {
return { name: "John" } as PersonNameConditional<withSurname>
}
}
// All good here ✅
上面的方法运行得很好,甚至IntelliSense也会根据收到的参数向我显示返回的类型,如下所示.
const result = getPerson(true) // { name: "John", surname: "Wic-k" }: PersonWithSurname
const result = getPerson(false) // { name: "John" }: Person
// All good here ✅
然而,在这里我遇到了一个问题,TS无法从响应中识别surname
.
const requestedSurname: boolean = req.query.withSurname
let result = getPerson(requestedSurname)
if ("surname" in result)
// All good here ✅
result.surname = result.surname.replace(/-/g, '')
if (result.surname)
// ❌ Property "surname" does not exist on type { name : string } | PersonWithSurname
result.surname = result.surname.replace(/-/g, '')
// the ideal usage
if (requestedSurname)
// ❌ Property "surname" does not exist on type { name : string } | PersonWithSurname
result.surname = result.surname.replace(/-/g, '')
return result;
难道不能使用条件变量吗?