Home > Software engineering >  Typescript: Ensure that function returns correct type depending on interface key
Typescript: Ensure that function returns correct type depending on interface key

Time:04-07

How can I type this so that it errors unless the returned value of price: t => t.price is a number (according to UData's interface):

// The prop value can be null, or a function which returns the 
// correct type (not `any`)
type PropTable<T, U> = Record<keyof U, null | ((t: T) => any)>

//
// Example use
//

interface TData {
    price: string
}

interface UData {
    price: number
}

// Should fail as the returned type is a string and "price" in 
// UData requires a number.
const props1: PropTable<TData, UData> = {
    price: t => t.price
}

// Should work as the returned type is a number which "price" in 
// UData requires.
const props2: PropTable<TData, UData> = {
    price: t => Number(t.price)
}

Playground

CodePudding user response:

I believe the solution here is to use a mapped type:

type PropTable<T, U> = {
    [key in keyof U]: null | ((t: T) => U[key])
}
  • Related