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