[英]Typescript: can't define return type of a function from multiple conditional typings
I'm tring to build a return type of a function from multiple conditional typings. 我想从多个条件类型中构建一个函数的返回类型。 What i'am trying to get as the returns of the function
buildKindsFor
is an object containing all kinds possible keys variation attached to a function. 我想要获得的函数
buildKindsFor
的返回是一个包含附加到函数的各种可能的键变体的对象。
Code sample will be better, in the first one everything is ok: 代码示例会更好,在第一个示例中一切正常:
type KindNames =
| 'one' | 'two' | 'three'
type KindShort<T extends KindNames> =
T extends 'one' ? 'o' : T extends 'two' ? 'tw' : 'th'
type KindPluralized<T extends KindNames> =
T extends 'one' ? 'ones' : T extends 'two' ? 'twos' : 'threes'
const buildKindsFor = <
K extends KindNames,
S extends KindShort<K>,
P extends KindPluralized<K>,
>(
kind: K,
fn: (kind: KindNames, obj: any) => any,
): {
[A in K]: () => any
} => {
throw new Error ('Yet to implement !')
}
But when I try to add an entry in the returns object, let's say the short version, everything breaks such as (the error is all over, in comments are some of the messages when i hover over in the IDE): 但是当我尝试在返回对象中添加一个条目时,让我们说短版本,所有内容都会中断(错误已全部结束,在评论中是我将鼠标悬停在IDE中时的一些消息):
const buildKindsFor = <
K extends KindNames,
S extends KindShort<K>, // Cannot find name K
P extends KindPluralized<K>, // 'KindPluralized' only refers to a type, but is being used as a value here
>(
kind: K,
fn: (kind: KindNames, obj: any) => any,
): {
[A in K]: () => any // ';' expected, ... and so on
[B in S]: () => boolean
} => {
throw new Error ('Yet to implement !')
}
The expected returns type for a call to let's say buildKindsFor ('one', dummyFn)
should be something like: 调用let的说明
buildKindsFor ('one', dummyFn)
的预期返回类型应该类似于:
{
one: () => any
o: () => boolean
ones: () => string
}
Thanks in advance for anyone who could point me what i am missing. 提前感谢任何可以指出我缺少的人。 Seb
勒布
This is a syntax error in your mapped type causing the parser to become unhappy all over the place. 这是映射类型中的语法错误,导致解析器在整个地方变得不快乐。 You can't make a mapped type with two indexes.
您不能使用两个索引创建映射类型。
{ [A in K]: () => any, [B in S]: () => boolean } // syntax error!
Either use an intersection 要么使用交叉点
{ [A in K]: () => any } & { [B in S]: () => boolean }
or make the indexer a union of the keys you care about: 或使索引器成为您关心的键的并集:
{ [A in K | S]: A extends K ? (() => any) : (() => boolean) }
Either way should clear up those errors. 无论哪种方式都应该清除这些错误。
As an aside, the second and third type parameters S
and P
are not really needed, unless I'm missing something. 另外,第二和第三类型参数
S
和P
并不是真正需要的,除非我遗漏了一些东西。 You can just replace S
with KindShort<K>
and P
with KindPluralized<K>
and it should work for you. 只需更换
S
与KindShort<K>
和P
与KindPluralized<K>
它应该为你工作。
Hope that helps; 希望有所帮助; good luck!
祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.