Take a look at this code snippet:
type Data = {
person: { id: number; name: string; age: number }
item: { id: number; name: string; price: number }
transaction: { id: number; personId: number; itemId: number; quantity: number }
}
type Action<T extends keyof Data> = {
type: T
payload: Data[T]
}
function fetchData<T extends keyof Data>(
action: Action<T>,
) {
const actionPayload = action.payload as Data[T] // <---- not functioning properly, only showing id.
switch (action.type) {
case "item":
const item = action.payload as Data["item"]
return `item is ${item.name}`
case "transaction":
const transaction = action.payload as Data["transaction"]
return `transaction is ${transaction.itemId}`
case "person":
const person = action.payload as Data["person"]
return `name is ${person.name}`
default:
return
}
}
const personAction: Action<"person"> = {
type: "person",
payload: { id: 1, name: "John", age: 30 },
}
const itemAction: Action<"item"> = {
type: "item",
payload: { id: 201, name: "Gadget", price: 49.99 },
}
const transactionAction: Action<"transaction"> = {
type: "transaction",
payload: { id: 1001, personId: 2, itemId: 201, quantity: 2 },
}
console.log(fetchData(personAction))
console.log(fetchData(itemAction))
console.log(fetchData(transactionAction))
As I attempt to delete this line of code:
const item = action.payload as Data['item'];
...and create a new constant above the switch case:
const actionPayload = action.payload as Data[T]
then utilize it like so:
case "person":
return `name is ${actionPayload.name}`
typescript raises the following issue:
Property 'name' does not exist on type '{ id: number; name: string; age: number; } | { id: number; name: string; price: number; } | { id: number; personId: number; itemId: number; quantity: number; }'.
and upon inspecting context
, only the id
field is present.
What causes this problem and how can it be resolved?