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.
You can specify a return value and use type assertion on the returned
someObjPlayground Link