代码
interface Order {
customer: Customer,
address: Address
}
interface Customer {
name: string
}
interface Address {
firstLine: string
}
interface OrderUpdateRequest {
key: 'customer'|'address',
value: Customer | Address
}
const myThing = {customer: {name: 'Bob'}, address: {firstLine: 'my street'}} as Order
const updateRequest = {key:'customer', value: {name : 'Dave'}} as OrderUpdateRequest
myThing[updateRequest['key']] = updateRequest['value']
背景
以上面的操场为例,我希望能够创建一个通用接口,它将接受customer
或address
作为键,然后如果键是customer
,则TS知道该值将是Customer
的实例.
当前问题
我无法更改订单上customer
的值,因为TypeScrip要求请求的value
与客户和地址一致
Type 'Customer | Address' is not assignable to type 'Customer & Address'.
Type 'Customer' is not assignable to type 'Customer & Address'.
Property 'firstLine' is missing in type 'Customer' but required in type 'Address'.(2322)
input.tsx(11, 5): 'firstLine' is declared here.
请注意,尽管第Infer the type value of a property based on the type value of another property in an array of object in TypeScript期的标题措辞相似,但情况和结果却大相径庭.
最新情况: Playground 2个 Solution Playground