0

Assume I have a type

type MyType = {
   'KEY1': 'ValueForKey1';
   'KEY2': 'ValueForKey2';
   'KEY3': 'ValueForKey3';
}

and I have function which takes values from MyType as {key: 'KEY1', value: 'ValueForKey1'}

function myFunc(entry: MyParamType<MyType>) {

}

Where I defined MyParamType as

type MyParamType<T> = {
    key: keyof T;
    value: T[keyof T]
};

This works fine for

myFunc({
    key: 'KEY1',
    value: 'ValueForKey1'
})

and fails as expected for

myFunc({
    key: 'KEY1',
    value: 'ValueForKey5' // should fail
})

The issue I am facing is it can take the value of any key instead of that particular key So

myFunc({
    key: 'KEY1',
    value: 'ValueForKey2'
})

succeeds instead of failing.

How do I add the conditional restriction that only the corresponding key should succeed?

Playground link.

2 Answers 2

2

You can define your method as:

function myFunc<K extends keyof MyType, V extends MyType[K]>(
  entry: {key: K, value: V}) {
// function body
}

Where you define two generic types K and V where V extends MyType[K], i.e. the value corresponds to the key.

See playground

Sign up to request clarification or add additional context in comments.

Comments

2

Adding a second type argument - the key - will do what you want. Then you can use it instead of T[keyof T]:

type MyType = {
  'KEY1': 'ValueForKey1';
  'KEY2': 'ValueForKey2';
  'KEY3': 'ValueForKey3';
}
function myFunc<T extends Partial<MyType>, K extends keyof T>(entry: {
  key: K,
  value: T[K]
}) {

}

// Fails
myFunc({
  key: 'KEY1',
  value: 'ValueForKey2'
})

// Works
myFunc({
  key: 'KEY1',
  value: 'ValueForKey1'
})

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.