Unique Code
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: 'Alice'}, address: {firstLine: '123 Main St'}} as Order
const updateRequest = {key:'customer', value: {name : 'Eve'}} as OrderUpdateRequest
myThing[updateRequest['key']] = updateRequest['value']
Description
Check out the Playground
Based on the playground above, I aim to develop a versatile interface that can accept either customer
or address
as a key. Additionally, TypeScript should recognize that if the key is customer
, the value would be an instance of Customer
.
Issue at Hand
I am encountering difficulties modifying the customer
field on the order due to TypeScript requiring the value
of the request to adhere to both Customer AND Address interfaces
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.
Please bear in mind that despite similarities in wording with another issue, the scenario and resolution are distinct. Check out this related thread for more information.
Update: Playground 2 Solution Playground