Skip to content

[SUGGESTIONS]Calculate everything can be calculated at compile time. #12104

Closed
@xialvjun

Description

@xialvjun

TypeScript Version: 2.0.3 / nightly (2.1.0-dev.201xxxxx)

Code

// A *self-contained* demonstration of the problem follows...
function abc(a: number) { 
  if (a === 1) {
    return {a:1}
  }
  if (a === 2) {
    return {b:2}
  }
  return {c:3}
}

console.log(abc(3).c)

Expected behavior:
The compiler know that abc(3) has the property c.
Actual behavior:
It doesn't.

My thoughts:
Since in abc(3), the argument is a known value, and abc doesn't rely on any outter closure, it can be calculated at compile time, the compiler should know the result has the property c.
And of course:

const arg1 = 3;
console.log(abc(arg1).c);  // it should work

let arg2 = 3;
console.log(abc(arg2).c);  // it shouldn't work

function abc2(a: number) {
  if (a === 1 && window.whatever === true) {
    return {a:1}
  }
  if (a === 2) {
    return {b:2}
  }
  return {c:3}
}
console.log(abc2(3).c);  // it shouldn't work

Just like the title: Calculate everything can be calculated at compile time.


In fact, the above is not what I really want. What I really want is JUST TRY. Try to run every part of the code. If it can go on, then we know the type, we can even know the result value. And we can even just replace the expression with the result value for a better running performance and a smaller bundled size.

We do not need a complex type system. What we need is just running my code and leave out what you do not know now, then tell me what I can type at next character.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions