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

Type limit operator for variable #44784

Closed
5 tasks done
andjsrk opened this issue Jun 28, 2021 · 1 comment
Closed
5 tasks done

Type limit operator for variable #44784

andjsrk opened this issue Jun 28, 2021 · 1 comment
Labels
Duplicate An existing issue was already created

Comments

@andjsrk
Copy link

andjsrk commented Jun 28, 2021

Suggestion

πŸ” Search Terms

type limit operator

βœ… 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

This feature limits type for variable.

  • Limited type should be assignable to original type.
  • The limitation is in effect within current scope.

πŸ“ƒ Motivating Example

When I was writing overloaded function, I thought I'm writing unnecessary code(like type guard) on runtime because I assumed the user always provide valid arguments.

So, why don't you use as keyword?

There are two ways to use as keyword.
First, you can redeclare variable with as keyword.
Second, you can put as keyword on EVERYWHERE the variable used.
I think the first way makes unnecessary variable.
And the second way is terrible as you know.

πŸ’» Use Cases

class A {}
class B extends A {
    foo() {}
}
const foo: A = new B();
if ('foo' in foo) {
    foo := B;
    console.log(foo.foo()); // no errors
}
function overloaded(type: 'array', array: Array<any>): undefined;
function overloaded(type: 'string', string: string): undefined;
function overloaded(type: 'array' | 'string', value: Array<any> | string) {
    if (type === 'array') {
        value := Array<any>;
        console.log(value.every(element => element !== undefined)); // no errors
    } else {
        value := string;
        console.log(value.substring(0, 5)); // no errors
    }
}
@jcalz
Copy link
Contributor

jcalz commented Jun 28, 2021

Duplicate of #10421

@andrewbranch andrewbranch added the Duplicate An existing issue was already created label Jun 28, 2021
@andjsrk andjsrk closed this as completed Jul 1, 2021
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

3 participants