typescript - 我可以在 typescript 中定义/链接类型到类吗?

标签 typescript

在 typescript 中,类中是否可以有“静态类型字段”?我知道以下内容无效,但只是为了让您了解我想要实现的目标:

class Collection<Item> {
  items: [Item];
  constructor() { this.items = [] }
  type ItemType = Item; // invalid
}
function for_each<Container>(
  container: Container,
  f: (val:Container.ItemType) => any // invalid
)
  { /* ... */ }
var strings = new Collection<string>();
var int_processor = function (val: number) {}
for_each(strings, int_processor); // I'd like an error here

我是 typescript 新手,我找不到是否存在执行此类操作的语法(有点像 C++ 中类内的 typedef)。希望它允许在最后一行出现错误,以便我可以在编译时捕获无法在 strings 上运行 int_processor

这可能吗?

最佳答案

回答原来的问题 - 你不能在类中定义类型别名。 Here's相关建议,实现可能性不大。


但看来您真正想要的是如何提取泛型类型参数。 您可以使用conditional types为此:

class Collection<Item> {
    items: Item[];
    constructor() { this.items = [] }
}

type GetItemType<T> = T extends Collection<infer ItemType> ? ItemType : never;

declare function for_each<Container>(
    container: Container,
    f: (val: GetItemType<Container>) => any
): void;

const strings = new Collection<string>();
const int_processor = function (val: number) { }
for_each(strings, int_processor); // Error: 'string' is not assignable to type 'number'

Playground

关于typescript - 我可以在 typescript 中定义/链接类型到类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59050895/

相关文章:

reactjs - 使用 Vite 的新 TypeScript React 应用程序 - JSX.IntrinsicElements 错误

macos - MacOS 上 Coda 中的 TypeScript 高亮显示

javascript - 将(旋转的)ImageOverlay 内的 X 和 Y 坐标转换为纬度和经度

reactjs - 类型字符串不可分配给类型

reactjs - 在 TypeScript 中键入 Redux 工具包的存储

angular - 运算符 '==' 不能应用于类型 'number' 和 'string'

javascript - angular2 @output 什么时候解决?

javascript - 如何专注于一个领域?

typescript - 在 type-graphql 中传递 typescript 类型问题

html - 在 angular7 中,如何在显示元素列表时更改 mat-select 的高度?