0

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

1 Answer 1

1

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 {
  // [...]
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.