Skip to content

Suggestion: int type #195

Closed
Closed
@fdecampredon

Description

Introducing int type could allows some error to be caught at compile time (like trying to index an array with a float) and perhaps improve performance of outputted javascript, to obtains true int, TypeScript could systematically emit a cas with |0 when a variable/parameter is an integer :

var i: int; 
var n: number;
var a: any = 1.2;
i = 1.1; // error;
i = n; // error
i = 3 / 4; // valid, type casted
i = a; // valid, type casted

var indexable: { [i: int]: bool } = {};
indexable[n] = true; // error
indexable[i] = true; // valid
indexable[i/2] = true; // valid, type casted
indexable[a] = true; // valid, type casted

function logInt(i: int) {
  console.log(i);
}

would emit

var n;
var i = i | 0;
var a = 1.2;
i = 1.1 // error;
i = n // error
i = (3 / 4 ) | 0; // valid, type casted
i = a | 0; // valid, type casted

var indexable= {};
indexable[n] = true; // error
indexable[i] = true; // valid
indexable[(i / 2) | 0] = true; // valid, type casted
indexable[a | 0] = true; // valid, type casted

function logInt(i: int) {
  i = i | 0;
  console.log(i);
}

There will perhaps be a problem with generic and method but I guess the compiler could in this case type cast when passing the parameter:

function add<T>(a: T,b: T): T {
  return a + b;
}  

var a = add(1, 2); // a is number value 3
var b = add<int>(1/2, 2); // b is int, value 2
var c = add(1/2, 2); // c is number, value 2.5

emit :

function add(a, b) {
  return a + b;
}
var a = add(1, 2); // a is number value 3
var b = add<int>((1/2)| 0, 2);
var c = add(1/2, 2); // c is number, value 2.5

also perhaps the compiler should always infer 'number' if there is not explicit type annotation

var n = 3 //number
var i: int  = 3 //int

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    Out of ScopeThis idea sits outside of the TypeScript language design constraintsSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions