在打字稿中,是否可以在类中使用“静态类型字段”?我知道以下内容是无效的,只是为了让您大致了解我要完成的工作:
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)。希望这将允许获得最后一行的错误,这样我就可以在编译的时候,我不能运行赶上int_processor
上strings
。
有可能吗?
要回答原始问题-您不能在类内定义类型别名。这是相关的建议,不太可能实现。
但是看来您真正要寻找的是如何提取泛型类型参数。您可以为此使用条件类型:
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'
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句