Mue
Mue

Reputation: 568

How to generically type an object in Typescript

I’ve got an object of settings and want to provide single key-value pairs to a function like so:

const settings = {
  time1: 40 * 60 * 60,
  time2: 10 * 60 * 60,
  breaks: [
    { limit: 6 * 60 * 60, length: 30 * 60 },
    { limit: 9 * 60 * 60, length: 15 * 60 },
  ],
}

// works
function changeSetting1<T extends keyof typeof settings>(details: {key: T, value: typeof settings[T]}): void {
//
}

// doesn't work
type func_details = <T extends keyof typeof settings>{key: T, value: typeof settings[T]}
function changeSetting2(details: func_details): void {

changeSetting1({key: "time1", value: 8 * 60 * 60})
changeSetting2({key: "time1", value: 8 * 60 * 60})

While it seems to work when I type it directly at the function, TypeScript complains that there is a ( expected when I first define the type func_details. What is the correct syntax for doing so?

TS Playground

Upvotes: 0

Views: 39

Answers (1)

D. Pardal
D. Pardal

Reputation: 6597

First of all, you have a syntax error. The type definition should be:

type func_details<T extends keyof typeof settings> = {key: T, value: typeof settings[T]};

Secondly, since the function accepts an argument with a generic type, the function itself must have a generic argument that satisfies the extends keyof typeof settings condition.

function changeSetting2<T extends keyof typeof settings>(details: func_details<T>): void {
  // [...]
}

Upvotes: 1

Related Questions