使用类型安全定义typescript泛型

Tim*_*Tim 33 generics typescript

您可以使用c#定义具有安全类型的泛型吗?

例如

public bool Foo<T>() where T : struct { /* */ }
Run Code Online (Sandbox Code Playgroud)

打字稿现在有泛型,但我可以执行类似的操作吗?

谢谢.

Tim*_*Tim 76

好吧,好像你可以这样做:

Foo<T extends IBar>() { /* */ }
Run Code Online (Sandbox Code Playgroud)

这似乎使所有调用都需要T来实现IBar.

  • +1 - 现场点.这取自泛型的Java实现 - `extends`关键字用于约束接口或类. (5认同)
  • 请注意,类型“实现” IBar接口不是必需的,它只能与它兼容。 (2认同)