Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

declare <typecast> syntax #49321

Closed
5 tasks done
PoolloverNathan opened this issue May 31, 2022 · 2 comments
Closed
5 tasks done

declare <typecast> syntax #49321

PoolloverNathan opened this issue May 31, 2022 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@PoolloverNathan
Copy link

Suggestion

πŸ” Search Terms

is:issue declare as

βœ… Viability Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

declare <typecast> syntax that replaces the type of the identifier used in the typecast. Ideally this would work inside an if statement to only replace the part of the union narrowed to by the if statement. TS2352 should be raised if it would be raised by a normal (non-declared) typecast.

πŸ’» Use Cases

When you know that a variable is a certain type, but Typescript doesn't (i.e. untyped libraries), you need to create a new variable and use typecasts. This creates an additional variable.

Test Cases

const x = 2;
declare x as string;
x // string
const x = RiggedMath.random(); // provides 0-0.5 or MyTwo, but is typed as () => number
if (x > 0.5) {
  declare x as RiggedMath.MyTwo;
}
x // number | MyTwo
@MartinJohns
Copy link
Contributor

MartinJohns commented May 31, 2022

Duplicate of #10421. It's the exact same suggestion, just different keywords.

you need to create a new variable and use typecasts. This creates an additional variable.

You can use assertion-functions instead. This creates no new variable. Only disadvantage is that you require a function, and it has a close-to-zero runtime impact.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label May 31, 2022
@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants