【问题标题】:Types not aligning in mapped array映射数组中未对齐的类型
【发布时间】:2021-06-20 11:01:44
【问题描述】:

以下面的简化代码示例为例(我已经从我的真实用例中简化了它以找到问题的根源):

type TStringWrapper<C extends string> = { wrappedString: C };

type TWrapIfArrayOfStrings<S> = S extends Array<string>
    ? {
        [K in keyof S]: TStringWrapper<S[K]>
    }
    : never;

我收到以下编译器错误:

Type 'S[K]' does not satisfy the constraint 'string'.
  Type 'S[keyof S]' is not assignable to type 'string'.
    Type 'S[string] | S[number] | S[symbol]' is not assignable to type 'string'.
      Type 'S[string]' is not assignable to type 'string'.

据我所知,这应该可以编译,因为S[K] 被保证是一个字符串,因为它前面有条件。如何重写它才能正常工作?

【问题讨论】:

  • 你能举例说明你将如何使用这种类型吗?

标签: typescript typescript-generics


【解决方案1】:

试试这个:

type TStringWrapper<C extends string> = { wrappedString: C };

type TWrapIfArrayOfStrings<S> = S extends Array<string>
    ? {
        [K in keyof S & number]: TStringWrapper<S[K]>
    }
    : never;

你知道S扩展Array&lt;string&gt;然后S的一个键是number而不是stringS[0], S[1] ...等等。

Here 是工作示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-05
    • 1970-01-01
    • 2014-08-13
    • 2013-05-26
    • 2014-08-11
    • 1970-01-01
    相关资源
    最近更新 更多