che*_*ica 7 type-safety typescript
我们有以下两个接口:
interface A {
foo: string;
bar: number;
}
interface B {
foo: string;
}
Run Code Online (Sandbox Code Playgroud)
如何将符合 A 的对象类型安全地转换为符合 B 的对象?
这不起作用:
const a = { foo: "baz", bar: 42 }
const b: B = {...a}
delete b.bar // <=== cannot remove "bar" because B has no "bar"
Run Code Online (Sandbox Code Playgroud)
我可以在没有类型安全的情况下做到这一点:
const a = { foo: "baz", bar: 42 }
const temp: any = {...a}
delete temp.bar
const b: B = temp
Run Code Online (Sandbox Code Playgroud)
我认为这有效:
const a = { foo: "baz", bar: 42 }
const b: B = {
...a,
bar: undefined
}
Run Code Online (Sandbox Code Playgroud)
但这不是我想要的,因为它分配undefined给b.bar,这可能会导致问题(例如 Firestore 不会接受它作为输入,因为它不允许未定义的值)。
有没有类型安全的方法来做到这一点?
Rad*_*iță 10
您可以做的一件事是destructuring assigment。与此类似的东西:
const a = { foo: "baz", bar: 42 }
const {foo, ...b}= a
Run Code Online (Sandbox Code Playgroud)
bwith 包含除 之外的所有属性foo。TS将能够使用推断与b兼容的类型B。