function myFunc(id: string) {
id = "(";
};
let id: string = ")";
if (id !== '(')
throw "Expected '(' in prototype";
myFunc(id);
if (id !== ')')
throw "Expected ')' in prototype";
如果我以内联方式进行更改,则不会出现以下错误
error TS2365: Operator '!==' cannot be applied to types '"("' and '")"'.
比较的内容无关紧要。可以使用任何字符串a,basdasd,cqwe等代替(和)
发生的是类型变窄。在传递第一个if语句之后,将类型限制id
为字符串文字“)”,因为否则将引发异常。
function myFunc(id: string) {
id = "(";
};
// Note that this function does nothing, but it's not the issue here
let id: string = ")";
if (id !== '(')
throw "Expected '(' in prototype";
// id is narrowed to "("
myFunc(id);
// now id and ')' does not have same type, hence the error
if (id !== ')')
throw "Expected ')' in prototype";
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句