如果我们有这样的类型:
interface Person {
name: string;
}
interface Agent extends Person {
code: number;
}有这样的代码:
const agent: Agent = {
name: 'name',
code: 123
}如何将类型Agent转换为Person并删除代码字段?当我尝试这样做的时候:
const person: Person = agent as Person
console.log(person) // Still contains the fields of agent这是一个简单的例子,但在我的实际使用中,对象有更多的字段。我也试过:
person: Person = {
...agent
}我看过的另一篇文章不适用于我的案例:在接口中用超类限制类型。
发布于 2022-02-22 13:58:25
铸造并不意味着铸件内部的真正价值会发生变化。开发人员应该告诉TypeScript“相信我,我知道里面是什么”。它只有在开发过程中才有意义,而不是在运行时。
对于开发部分,也许实用程序类型会有所帮助。例如,您可以这样做(如果您想在Agent中保留Person中的某些字段):
type Person = Pick<Agent, "name"|"address">;https://stackoverflow.com/questions/71222416
复制相似问题