我有一个这样定义的类
class Foo {
value: string | null;
constructor(){
this.value = null;
}
private ensureValueExists():this.value is string{ //type predicate is not legal
this.value = "bar";
return true;
}
doStuffWithValue(){
this.ensureValueExists();
return 5 + this.value; //ERROR, this.value can be null
}
}
我希望 EnsureValueExists 方法能够告诉编译器 this.value 确实是一个字符串并且可以安全使用。
是否有特殊的语法可以使用,或者目前对于方法来说 TS 无法实现?
您可以使用断言方法 https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#assertion-functions这缩小了this
。文档中对此的支持并不是特别明确,尽管commit https://github.com/microsoft/TypeScript/pull/32695/commits/0599f848575dcfbda5730c446003f4e59411446d有关联微软/TypeScript#32695 https://github.com/microsoft/TypeScript/pull/32695,实现断言函数的 PR,证明了这是可能的。
所以在你的情况下它看起来像:
private ensureValueExists(): asserts this is { value: string } {
this.value = "bar";
}
(请注意,您不能在断言函数/方法中返回任何内容),然后执行以下操作:
doStuffWithValue() {
this.ensureValueExists();
return 5 + this.value; // okay
}
}
肯定有caveats https://github.com/microsoft/TypeScript/issues/34596#issuecomment-544208587与断言函数和方法相关联,但由于您只在this
,你不会在这里遇到他们。
Playground 代码链接 https://www.typescriptlang.org/play?ts=4.3.5#code/MYGwhgzhAEBiD29oG8BQ1oDcwgK4FMAuaCAFwCcBLAOwHNoAfaa3EEAbnWmHmrPNzBS8cgAoAlCi4ZSAC0oQAdNjz5oAXmasOXAL5cADlWyk1+PrnL4AajgIBRAB4LSECcUgR85V9DkLoAOQsOyISChp6XSkMGXklFQINaAAiACMwchTODH0MABN4AGVSXAAzMoB1SjlbVQkY2P8lcwhLG1CnFzdxHNirUvJqaABWaABqP3jlUPYMAHp56HgAazAATz1UfVQgA
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)