有没有办法防止在TypeScript中发生“最常见类型”分辨率?(Is there a way to prevent “best common type” resolution from happen

编程入门 行业动态 更新时间:2024-10-28 15:24:48
没有办法防止在TypeScript中发生“最常见类型”分辨率?(Is there a way to prevent “best common type” resolution from happening in TypeScript?)

有没有办法防止TypeScript中出现以下类型的问题:

interface Consumer<a> { consume(value: a): void } function consumeValue<a>(consumer: Consumer<a>, value: a) { consumer.consume(value); } var consumer : Consumer<number> = { consume(value) { console.log('Number: ' + value); } } consumeValue(consumer, 'Hey!'); // <-- this is legit, thank to the best common type resolution that really works!

Is there a way to prevent the following sort of problems in TypeScript:

interface Consumer<a> { consume(value: a): void } function consumeValue<a>(consumer: Consumer<a>, value: a) { consumer.consume(value); } var consumer : Consumer<number> = { consume(value) { console.log('Number: ' + value); } } consumeValue(consumer, 'Hey!'); // <-- this is legit, thank to the best common type resolution that really works!

最满意答案

除了手动指定泛型类型参数之外,目前还没有一种直接的方法来阻止这种情况:

consumeValue<number>(consumer, 'Hey!');

作为TypeScript添加联合类型的一部分,以及作为命令行标志的单独提议 , 正在讨论对此行为的更改。

There currently isn't a good straightforward way to prevent this other than to manually specify the generic type parameters:

consumeValue<number>(consumer, 'Hey!');

A change to this behavior is under discussion as part of TypeScript adding union types, and as a separate proposal for a command-line flag.

更多推荐

本文发布于:2023-07-07 13:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1063903.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:没有办法   最常见   分辨率   发生   类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!