TypeScript 无法通过另一个变量推断唯一符号类型

pdsfdshx  于 3个月前  发布在  TypeScript
关注(0)|答案(4)|浏览(46)

字面量如0可以正确推断,但唯一符号不能。

TypeScript版本: 3.7.x-dev.20191224
搜索词:
代码

let revision: symbol;
const rev = revision = Symbol();
rev === revision;

预期行为:

Type rev是唯一符号。

实际行为:

Type rev是符号。甚至无法声明rev是一个唯一符号。

** playground链接:**https://www.typescriptlang.org/play/index.html?ts=3.8.0-dev.20191224&ssl=1&ssc=1&pln=3&pc=18#code/DYUwLgBATiBuCWBneB7AdgLgogngWwCMVgBuAKAGN1FIZYIBeaOJVNRiAZXyOAAoAlOTqMGTOq3QkgA
相关问题:

vlf7wbxs

vlf7wbxs1#

为了确保我理解正确。你是说这个按照你的预期工作:

let wideNumber: number;
const narrowNumber = wideNumber = 0; 
// const narrowNumber: 0 👍

但是这个没有:

let wideSymbol: symbol;
const narrowSymbol = wideSymbol = Symbol();
// const narrowSymbol: symbol 😕

同样,这个按照你的预期工作:

const narrowNumber = 0;
// const narrowNumber: 0
const alsoNarrowNumber = narrowNumber;
// const alsoNarrowNumber: 0 👍

但是这个没有:

const narrowSymbol = Symbol();
// const narrowSymbol: typeof narrowSymbol
const alsoNarrowSymbol = narrowSymbol;
// const alsoNarrowSymbol: symbol 😕

Playground链接
对吗?

bvjxkvbb

bvjxkvbb2#

const alsoNarrowSymbol = narrowSymbol;
// const alsoNarrowSymbol: symbol 😕
这不是我的意图,但可能是合法的。

daolsyd0

daolsyd03#

可能有些相关。unique symbol具有一些奇怪的扩宽规则
#32242
即使是恒等函数也不安全。( <T>(t:T)=>T )

sh7euo9m

sh7euo9m4#

Just hit a similar widening issue to this one and the one described by @AnyhowStep on #32242 (now closed). A unique symbol ( typeof foo ) becomes just symbol when returned from a generic function of the following signature:

function reduce<T>(fn: (value: T, acc: T) => T, initial: T): T {}

String literal types are not widened by this construct, but unique symbol is. 😕

相关问题