[英]How to have TypeScript generic function with type argument being keyof an object have return type of that object's key's value
I have a several object types:我有几个 object 类型:
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:还有一个包含一些键的主类型,这些 object 类型作为这些键的值如下:
type Master = {
key1: Slave
key2: AnotherSlave
}
I have a generic function:我有一个通用的 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: someObj 保证具有来自Master[T]
值的类型,换句话说:
If the key is key1
, someObj
is the type of Slave
.如果 key 是key1
, someObj
是Slave
的类型。 If the key is key2
, someObj
is the type of AnotherSlave
.如果 key 是key2
, someObj
是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.无论如何,我已经根据 someObj 的外部调用的内容编写了类型,因此可以保证具有该类型。
I naively tried return someObj as Master[T]
but it errs Type 'T' cannot be used to index type 'Master'
.我天真地尝试return someObj as Master[T]
但它错误Type 'T' cannot be used to index type 'Master'
。
How can I make the function return strongly typed key's value type?如何使 function 返回强类型键的值类型? I'm on TypeScript 4.6.3.我在 TypeScript 4.6.3 上。
You can specify a return value and use type assertion on the returned someObj
您可以指定返回值并在返回的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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.