typescript - 提取泛型接口(interface)的属性类型仍然需要不必要的泛型类型

标签 typescript typescript-generics

当我有一个具有这样的泛型的接口(interface)时:

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

并尝试提取属性类型a使用I1['a'] , typescript 抛出以下错误:

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

这应该没问题吧,因为提取的属性类型实际上并不依赖于 <S> ?要么我无法理解 Typescript 的实际工作原理,要么这确实应该没问题。

Playground Link

最佳答案

属性a类型不依赖于S,但您不能省略类型参数作为 lookup 的一部分。一些选项:

1.) 将S设置为未知

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
// doesn't make too much sense in this particular case

Here is a sample

关于typescript - 提取泛型接口(interface)的属性类型仍然需要不必要的泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59576819/

相关文章:

javascript - TypeScript 编译上下文中包含 app.component.ts 的错误

angular - 在没有包装器 ViewChild 的情况下从组件代码访问 ng-content

typescript - 如何打开 typescript 通用内部类型

node.js - `repository.create` 去除既是数组又是嵌入对象的列的值

Angular:不支持此类型作为注入(inject) token

typescript - 当我忽略泛型类型定义时,为什么 typescript 不会提示?

javascript - 是否可以从 typescript 接口(interface)创建一个等效的 joi ?

typescript - TypeScript 条件类型的映射与受约束的泛型不同吗?

typescript - 如何访问嵌套对象类型的公共(public)属性,这些对象本身是使用泛型类型参数访问的

Angular 6查找并删除对象