Skip to content
This repository has been archived by the owner on Jan 25, 2022. It is now read-only.

Can Optional Chaining imitate swift style? #126

Closed
0x30 opened this issue Nov 8, 2019 · 3 comments
Closed

Can Optional Chaining imitate swift style? #126

0x30 opened this issue Nov 8, 2019 · 3 comments

Comments

@0x30
Copy link

0x30 commented Nov 8, 2019

TypeScript - issues 34970

I think I should bring it up here

Search Terms

  • swift style
  • Swift if let statement
  • Optional Chaining

Suggestion

  1. The left-hand side of an assignment expression may not be an optional property acces
  2. if let style,determine whether it is optional and obtain the object

Use Cases

for Suggestion 1

The 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?

for Suggestion 2

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
}
@jridgewell
Copy link
Member

foo.foo?.name = "hello"

Optional assignment is discussed in #18.

if let foo1 = foo?.foo { … }

See https://github.com/tc39/proposal-Declarations-in-Conditionals

@0x30
Copy link
Author

0x30 commented Nov 8, 2019

foo.foo?.name = "hello"

Optional assignment is discussed in #18.

if let foo1 = foo?.foo { … }

See https://github.com/tc39/proposal-Declarations-in-Conditionals

@jridgewell ok. thanks. I went to have a look. The proposal is already very good

@claudepache
Copy link
Collaborator

Closing this issue per #126 (comment) above.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants