提取通用接口的属性类型仍然需要不必要的通用类型。

huangapple go评论77阅读模式
英文:

Extracting types of properties of generic interfaces still requires unnecessary generic type

问题

When I have an interface with a generic as such:

   interface I1<S> {
      a: string;
      b: genericType<S>;
}

and try to extract the type of property a using I1['a'], TypeScript throws the following error:

TS2314: Generic type 'I1<S>' requires 1 type argument(s).

Should this not be fine since the extracted property type is not actually dependent on S? Either I am failing to understand how TypeScript actually works or this should indeed be okay.

Playground Link

英文:

When I have an interface with a generic as such:

   interface I1&lt;S&gt; {
      a: string;
      b: genericType&lt;S&gt;
}

and try to extract type of property a using I1[&#39;a&#39;], typescript throws the following error:

TS2314: Generic type &#39;I1&lt;S&gt;&#39; requires 1 type argument(s).

Should this not be fine since the extracted property type is not actually dependent on &lt;S&gt;? Either I am failing to understand how Typescript actually works or this should indeed be okay.

Playground Link

答案1

得分: 2

属性 a 的类型与 S 无关,但你不能在 lookup 的一部分中省略类型参数。一些选项:

1.) 将 S 设置为 unknown

type T1 = I1<unknown>["a"] // string

2.) 在接口中为 S 声明默认值

interface I2<S = unknown> {
  a: string;
  b: S;
}

type T2 = I2["a"] // string

3.) 保持通用性

type T3<S> = I1<S>["a"] // T3<S> = string
// 在这种特殊情况下并不太有意义

这里有一个示例

英文:

Property a type is not reliant on S, but you cannot omit the type parameter as part of the lookup. Some options:

1.) Set S to unknown

type T1 = I1&lt;unknown&gt;[&quot;a&quot;] // string

2.) Declare a default for S in the interface

interface I2&lt;S = unknown&gt; {
  a: string;
  b: S
}

type T2 = I2[&quot;a&quot;] // string

3.) Keep it generic

type T3&lt;S&gt; = I1&lt;S&gt;[&quot;a&quot;]  // T3&lt;S&gt; = string
// doesn&#39;t make too much sense in this particular case

Here is a sample

答案2

得分: 0

以下是翻译好的代码部分:

interface I1<S> {
    a: string;
    b: S;
}

// 在创建对象时需要指定S的类型:
// 请注意,下面的例子中,我为S泛型类型参数指定了string类型,但您可以选择任何您想要的类型作为“b”的类型。
const i1object: I1<string> = { a: "a", b: "b" };
const i1object2: I1<number> = { a: "a", b: 5 };
英文:

It should be:

interface I1&lt;S&gt; {
      a: string;
      b: S;
}

and you need to give the type of S when making the object:

notice I gave string type for the S generic type parameter below, but this can be any type you want the "b" to be.

const i1object: I1&lt;string&gt; = { a: &quot;a&quot;, b: &quot;b&quot; };
const i1object2: I1&lt;number&gt; = { a: &quot;a&quot;, b: 5 };

huangapple
  • 本文由 发表于 2020年1月3日 18:21:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/59576819.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定