TypeScript版本: 3.5.3(也尝试过@next
)
搜索词: const symbol property "not assignable to type"
代码
/*
* For reasons of how the JSON is converted, I'm using Symbols to hide certain properties.
*/
class Server {
public auth: string | null = null;
}
/** `tsc` complains about this[AUTH_PROP] even though it must always be a string inside the `if()` */
const AUTH_PROP = Symbol();
class TestSymbol {
private readonly [AUTH_PROP]: string | null = null;
public readonly server: Server | null = null;
public get auth(): string | undefined {
if (this[AUTH_PROP] !== null) {
return this[AUTH_PROP];
}
if (this.server && this.server.auth) {
return this.server.auth;
}
return undefined;
}
}
/** same thing with a string literal and it works */
class TestNoSymbol {
private readonly _auth: string | null = null;
public readonly server: Server | null = null;
public get auth(): string | undefined {
if (this['_auth'] !== null) {
return this['_auth'];
}
if (this.server && this.server.auth) {
return this.server.auth;
}
return undefined;
}
}
/** same thing with a const string and it fails */
const AUTH_PROP_S = '_auth';
class TestConstString {
private readonly [AUTH_PROP_S]: string | null = null;
public readonly server: Server | null = null;
public get auth(): string | undefined {
if (this[AUTH_PROP_S] !== null) {
return this[AUTH_PROP_S];
}
if (this.server && this.server.auth) {
return this.server.auth;
}
return undefined;
}
}
预期行为:
所有这三个版本都应该没问题,不会出现tsc
错误。const
的值永远不会改变,所以它必须始终是string
语句内的if()
。
实际行为:
Type 'string | null' is not assignable to type 'string | undefined'.
Type 'null' is not assignable to type 'string | undefined'.
Playground链接:https://is.gd/V7Jai9
相关问题: 不确定
3条答案
按热度按时间kb5ga3dv1#
在不使用URL缩短器的情况下进行Playground。我猜是因为缩小是在语法上完成的,而
this[constVar]
不是缩小的候选者?qqrboqgw2#
请问目前通过类似这种表达式缩小范围的状态如何?
bybem2ql3#
至少对于字符串,这是对计算属性的控制流的有意限制。对于符号来说可能也是一样的。尽管如此,我们可能能够对具有字面类型的计算属性稍微聪明一些,而不是实际的字面量。我不认为检测字面类型与仅检测字面量之间会有很大的复杂性增加。