onClick={() => { │ │┃ 235 │ │ │ │ │ │ │ │ │ │ │ if (platform) { │ │┃ 1 │ │ │ │ │ │ │ │ │…
- User
onClick={() => { │
│┃ 235 │ │ │ │ │ │ │ │ │ │ │ if (platform) { │
│┃ 1 │ │ │ │ │ │ │ │ │ │ │ │ window.ym(platform.analytics.yandex_metrika_id, 'reachGoal', 'show_full'); │
│┃ 2 │ │ │ │ │ │ │ │ │ │ │ } │
│┃ 3 │ │ │ │ │ │ │ │ │ │ │ setVisible() │
│┃ 4 │ │ │ │ │ │ │ │ │ │ }rewrite this ts in modern way
- Assistant
Certainly! To rewrite this TypeScript code snippet in a modern and clearer way, you can use optional chaining and concise function bodies. Here's a possible refactored version:
onClick={() => { platform?.analytics.yandex_metrika_id && window.ym(platform.analytics.yandex_metrika_id, 'reachGoal', 'show_full'); setVisible(); }}Explanation:
-
Optional Chaining (
?.): This allows you to safely access deeply nested properties. If any segment of the chain isundefinedornull, it will short-circuit and returnundefinedinstead of throwing an error. Here,platform?.analytics.yandex_metrika_idchecks if each part of the chain exists before attempting to accessyandex_metrika_id. -
Logical AND (
&&): This is used here to execute the function call only ifyandex_metrika_idis truthy. -
Concise Function Bodies: The code is simplified without unnecessary
ifstatements, making it more readable.
-