I am very happy with the long-awaited typescript Optional Chaining is online. But when I use it, there are some places that make me feel that I am not comfortable with it. I sincerely hope that can improve it...
if let style,determine whether it is optional and obtain the objectThe following code is not allowed in typescript 3.7.2.It's going to make a The left-hand side of an assignment expression may not be an optional property access
mistake
class Foo{
foo: Foo | undefined
name: String | undefined
}
let foo = new Foo()
// next line. ~~ The left-hand side of an assignment expression may not be an optional property access
foo.foo?.name = "";
But similar code, swift works well
class Foo{
var name: String?
var foo: Foo?
}
let foo = Foo()
foo.foo?.name = "hello"
In view of this, do we have any plans to solve this problem at present?
About judging optional variables and using it,The current practice of TS is
if(foo?.foo) {
/// foo.foo is non optional
}
In swift, there is a way to turn optional into non optional.
if let foo1 = foo?.foo {
// -- foo1 is non optional
}
Can be used in 'kotlin'
foo?.foo?.let{ foo1 ->
// -- foo1 is non optional
}
If you judge a method result. In order not to call the calculation twice, you need to replace the code with.
const value = foo?.foo()
if(value) {
// -- value is non optional
}
This is the wrong place to ask for changes to the ECMAScript spec. TypeScript only implements the spec and has no intention to add new language features on top of it (other than static types).
Thanks, I understand
Most helpful comment
This is the wrong place to ask for changes to the ECMAScript spec. TypeScript only implements the spec and has no intention to add new language features on top of it (other than static types).