How to have TypeScript generic function with type argument being keyof an object have return type of that object's key's value

2.2k Views Asked by At

I have a several object types:

type Slave = {
  myKey:string
}

type AnotherSlave = {
  anotherKey:string
}

And a master type that contains some keys, and these object types as those keys' values as below:

type Master = {
  key1: Slave
  key2: AnotherSlave
}

I have a generic function:

myFunc<T = keyof Master>(key:T){
  const someObj = {} // external call that returns "any" type
  return someObj; // I want to cast it to some strongly type here.
}

The someObj is guaranteed to have the type from Master[T]'s value, in other words:

If the key is key1, someObj is the type of Slave. If the key is key2, someObj is the type of AnotherSlave. I've wrote the types depending on what's coming from the external call of someObj anyway so it's guaranteed to have that type.

I naively tried return someObj as Master[T] but it errs Type 'T' cannot be used to index type 'Master'.

How can I make the function return strongly typed key's value type? I'm on TypeScript 4.6.3.

1

There are 1 best solutions below

0
asnaeb On

You can specify a return value and use type assertion on the returned someObj

function myFunc<T extends keyof Master>(key:T): Master[T] {
  const someObj = {}
  return someObj as Master[T];
}

const test = myFunc("key1") // <-- type is Slave

Playground Link