official handbook and record some important knowledges about TypeScript.">

TypeScript Basics | Wendy's Corner

TypeScript Basics

  |   Source

This is a brief reading note for TypeScript official handbook.

Gulp Setup

Gulp can be used with TypeScript to provide powerful compiling process. See here for a detailed description.

My new project requires Typescript, Jade and SASS. Here is a sample gulpfile.js:

var gulp = require("gulp");
var ts = require("gulp-typescript");
var tsProject = ts.createProject("tsconfig.json");
var jade = require("gulp-jade");
var sass = require("gulp-sass");

gulp.task("sass",function() {
    return gulp.src('src/styles/*.scss')
    .pipe(sass().on('error',sass.logError))
    .pipe(gulp.dest('dist/styles'));
})

gulp.task("typescript", function () {
    return tsProject.src('src/scripts/*.ts')
        .pipe(ts(tsProject))
        .pipe(gulp.dest("dist/scripts"));
});

gulp.task("jade",function() {
    return gulp.src('src/templates/*.jade')
        .pipe(jade())
        .pipe(gulp.dest("./dist"));
})

gulp.task('default',['sass','typescript','jade']);

And the tsconfile.json, just for future reference:

{
    "files": [
        "src/scripts/main.ts",
        "src/scripts/test.ts"
    ],
    "compilerOptions": {
        "noImplicitAny": true,
        "target": "es5"
    }
}

Types and Variables

Number

Integer, Floating Point, Hexadecimal and Decimal Literals can all be declared as number type.

let decimal: number = 6; //declare a variable called 'decimal', with value equaling to 6

String

Template Strings can be used to span multiple lines and have embedded expressions. Also + can be used to concatenate strings with variables.

Remember to use lower case string.

Example:

//Using `` to provide break line effect
let fullName: string = `Bob`;
let age: number = 37;
let sentence: string = `Hello, my name is ${fullName}.

I'll be ${age+1} years old next month.`
let sentence: string = "Hello, my name is " + fullName + ".\n\n" + "I'll be " + (age+1) + " years old next month."

Above code generates following js code. Notice the result of \n\n:

var fullName = "Bob";
var age = 37;
var sentence = "Hello, my name is " + fullName + ".\n\nI'll be " + (age + 1) + " years old next month.";
var sentence2 = "Hello, my name is " + fullName + ".\n\n" + "I'll be " + (age + 1) + " years old next month.";

Array & Tuple

To create an array, just use [] to construct array, or use Array<elemType> to do so: let list: number[] = [1,2,3]

To create a tuple (mixed type of variables), declare it first, then insert element to it:

let x: [string, number];
x = ['hello', 10]; //type must match
x[1] = 3; //OK to insert element to each position

Enum

In Java, Enum is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Java example is below:

public enum Day{
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

Similarly in typescript, an enum is defined by a group of constants (number, string, key-value pair, etc) using enum {}. User can create an instance with one constant from an enum constructor.

enum begin numbering elements starting from 0, It's ok to manually set corresponding number

Example:

enum Color{Read, Green, Blue};
let c: Color = Color.Green;
alert(c);

Code above will generate following JS code:

var Color;
(function (Color) {
    Color[Color["Read"] = 0] = "Read";
    Color[Color["Green"] = 1] = "Green";
    Color[Color["Blue"] = 2] = "Blue";
})(Color || (Color = {}));
;
var c = Color.Green;
alert(c);

Example with Assigned Index:

enum Color{Read=2, Green=8, Blue=10};
let c: Color = Color.Green;
let cname: string = Color[1]
alert(c);
alert(cname)

Code above will generate:

var Color;
(function (Color) {
    Color[Color["Read"] = 2] = "Read";
    Color[Color["Green"] = 8] = "Green";
    Color[Color["Blue"] = 10] = "Blue";
})(Color || (Color = {}));
;
var c = Color.Green;
var cname = Color[1];
alert(c);
alert(cname);

Any & Void

Any is used to describe the variables with unknown type, like data from user or 3rd party. Use any to let variable passing compiler's type-checking:

let notSure: any = 4;
let notSure2: any = [2, 'test', false]
//Following two methods can pass compiler but will getting error in running time, if methods actually do not exist
notSure.ifItExists();
notSure.toFixed();
notSure2.isItExists();
alert(notSure2);

let Sure: Object = 4;
Sure.toFixed();

In code above, first part of code can work without error reported from compiler. That's because any can pass any type-checking from compiler. However, second part of code will get compiler error error TS2339: Property 'toFixed' does not exist on type 'Object'(And you can see error reported in VSCode if you use it). That's because Object only allow you to assign any value to variable, but you can't call method on them, even though variable has that method.

Void is similar as the one in Java: if a function has void keyword, this function will not return anything. You can only assign null or undefined to void variable, otherwise you will get compiler error:

/*
If you don't user null or undefined, you will get following error in compiler:
error TS2322: Type 'number' is not assignable to type 'void'.
*/
let unusable: void = null;
function voidtest(): void{
    alert('this is a void test');
}

Type Assertion

Similar as cast in other languages, type assertion can be used to pass compiler's type checking. It should be used when certain type checking has been down and there is a guarantee of correct type.

<type>variable and variable as type can all be used to do type assertion. JSX only use variable as type style:

let typeassertion: string = "test type assertion string";
let strlength: number = (<string>typeassertion).length;
let strlength2: number = (typeassertion as string).length;
console.log(strlength);
console.log(strlength2);
Comments powered by Disqus