繁体   English   中英

Typescript:无法从多个条件类型中定义函数的返回类型

[英]Typescript: can't define return type of a function from multiple conditional typings

我想从多个条件类型中构建一个函数的返回类型。 我想要获得的函数buildKindsFor的返回是一个包含附加到函数的各种可能的键变体的对象。

代码示例会更好,在第一个示例中一切正常:

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 !')
}

但是当我尝试在返回对象中添加一个条目时,让我们说短版本,所有内容都会中断(错误已全部结束,在评论中是我将鼠标悬停在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 !')
}

调用let的说明buildKindsFor ('one', dummyFn)的预期返回类型应该类似于:

{
  one: () => any
  o: () => boolean
  ones: () => string
}

提前感谢任何可以指出我缺少的人。 勒布

这是映射类型中的语法错误,导致解析器在整个地方变得不快乐。 您不能使用两个索引创建映射类型。

{ [A in K]: () => any, [B in S]: () => boolean } // syntax error!

要么使用交叉点

{ [A in K]: () => any } & { [B in S]: () => boolean }

或使索引器成为您关心的键的并集:

{ [A in K | S]: A extends K ? (() => any) : (() => boolean) }

无论哪种方式都应该清除这些错误。


另外,第二和第三类型参数SP并不是真正需要的,除非我遗漏了一些东西。 只需更换SKindShort<K>PKindPluralized<K>它应该为你工作。


希望有所帮助; 祝好运!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM