The objective is to create a new keyword 'int' that has the same semantics as the named type 'number.' I know that I can achieve the same behavior by using the type 'number' but I have been specifically asked to implement a new keyword in typescript. I am interviewing for a research project at my school.

An example use-case would be the following:

function add(x:int, y:int) {
  return x + y; 
}

I have been struggling to achieve this exact use-case. I have spent several hours going through the documentation.

I have read through the Types, Classes and Interfaces sections to try and figure out how to do this; no luck thus far.

I know I can achieve something similar using an interface like so:

interface int {
   n: number;
}

But I'd have to implement the function like this:

function add(x:int, y:int) {
   return x.n + y.n;
}

I am completely new to typescript so any direction is greatly appreciated - thanks.

A few basic examples on typescriptlang.org

有帮助吗?

解决方案

Based on the question, your professor has realised a limitation of TypeScript.

He has specifically asked you to make an add function. This is important because TypeScript doesn't support overloading of operators (such as +).

However, you can write a function that accepts two ints and returns an int using the unary add operator as shown below. Only the code inside the function needs to understand there is odd stuff going on. Everything outside of the function thinks ints exist.

This wouldn't stop you from passing floats using the int type.

interface int extends Number {

}

function add(x: int, y: int) : int {
    return +x + +y;
}

var a: int = 1;
var b: int = 2;

var c = add(a, b);

其他提示

According to http://typescript.codeplex.com/workitem/119, you can use

interface int extends number {}

You also might be interesting in feature: int and float types.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top