Skip to content

How to handle typing of mutated let variables or function parameters? #64

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

Closed
justingrant opened this issue Sep 30, 2021 · 3 comments
Closed

Comments

@justingrant
Copy link
Contributor

A common pattern in our current polyfill code is to reassign variables and parameters. How should we work around TS's limitation that mutating a variable doesn't change its type from TS's perspective?

For example: (TS playground)

function toString(a: unknown) {
  a = String(a);
  return a;
  // expected return type: String
  // actual return type: unknown
}

toString(42).includes('4')
// ^^ Object is of type 'unknown'.(2571)

// explicitly declaring a return type doesn't work either
function toString2(a: unknown): string {
  a = String(a);
  return a;
  // ^^ Type 'unknown' is not assignable to type 'string'.(2322)
}

There is apparently a future TS proposal microsoft/TypeScript#45870 which may fix this. I commented there to ask if it will help us.

cc @12wrigja

@12wrigja
Copy link
Contributor

Hmm - yes this is a bit problematic.

One potential solution we could use is something like this:

playground with type assertion functions.

That being said, this isn't great given that it slightly bloats code-size and runtime as those extra checks have to be included. Internal to Google, we have a system like this that removes these checks in production builds, and we could maybe replicate small parts of it here (using DEBUG) .

Alternatively, could we simply avoid this pattern and rewrite to new variables? Are we really saving that much memory by mutation parameter variables?

@ptomato
Copy link
Contributor

ptomato commented Sep 30, 2021

Alternatively, could we simply avoid this pattern and rewrite to new variables? Are we really saving that much memory by mutation parameter variables?

Agreed, we can even turn on no-param-reassign in eslint and just catch all instances of this at once.

@12wrigja
Copy link
Contributor

We fixed this: eslintrc.yml only has that rule turned off in tests.

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

No branches or pull requests

3 participants