有没有办法防止在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.
更多推荐
发布评论