I recently encountered a situation where I needed to define a type with an id
field (string) and an oldId
field (number), but I wanted these fields to be exclusive.
For example:
{ id: "1234", name: "foo" }
{ oldId: 1234, name: "bar" }
I attempted the following code:
export type WithIdUnique<T> = T & ({ id: string } | { oldId: number })
export type ProductUnique = WithIdUnique<{
name: string
}>
const product1Unique: ProductUnique = {
oldId: 12345,
name: "foo"
}
const product2Unique: ProductUnique = {
id: "12345",
name: "bar"
}
This implementation worked perfectly. However, when passing it as a parameter, I encountered an issue:
import { ProductUnique } from 'product'
export const someTestFunction = (productParam: ProductUnique) => {
return product.id
}
The error message received was:
Property 'id' does not exist on type 'Product'.