Typescript: Difference between revisions

From bibbleWiki
Jump to navigation Jump to search
Line 104: Line 104:
* Never (e.g. for infinite loop return types)
* Never (e.g. for infinite loop return types)
* Any (e.g. for when using types not guaranteed from other libraries)
* Any (e.g. for when using types not guaranteed from other libraries)
* Tuple (e.g. let myTuple: [number, string] = [25,'truck'] not other elements can have only number of string e.g. myTuple[2] = 'fred')


Union types
Union types

Revision as of 04:53, 11 July 2020

Introduction

TypeScript is a typed language which produces javascript.

e.g.

let myString = "fred";
let myBoolean = true;

function createMessage(name:string) {

}

Typescript supports classes and access modifiers

class Person {
   
   name: string
   lastName: string
   
   public Person(name:string) {
       this.name = name;
   }

   public void setLastName(lastName: string) {
       this.lastName = lastName;
   }
}

Configuration

tsconfig

You can set the options for the compiler you can specify a tsconfig.json file. By using

tsc --init

you get a default file.

You can inherit tsconfigs from parent directories. This compiles all *.ts files in this directory and child directories.

{
  "extends": "../tsconfig.base",
  "compilerOptions": {
    "removeComments": true
  },
  "include": [
    "./**/*.ts"
  ]
}

Webpack Configuration

The ts-loader module allows recompiling of the type script and you need to install it if using.

module.exports = {
  entry: './app/app.ts',
  devtool: 'inline-source-map'
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/
      }
    ]
  },
  resolve: {
    extensions: ['.tsx', '.ts', 'js']
  },
  output: {
    filename: 'bundle.js'
  },
  devServer: {
    inline: false
  }
};

Data Types

No more var

Don't use var but instead use

let

or

const

Base Data Types

The following types are available

  • Boolean
  • Number
  • String
  • Array
  • Enum (not in javascript)

Other types

  • void
  • null
  • undefined
  • Never (e.g. for infinite loop return types)
  • Any (e.g. for when using types not guaranteed from other libraries)
  • Tuple (e.g. let myTuple: [number, string] = [25,'truck'] not other elements can have only number of string e.g. myTuple[2] = 'fred')

Union types This allows more than type e.g.

let number_string : string | number

Not good if you ask me. However maybe useful for strings e.g.

let null_string : string | null

By default the null is not allowed to be assigned without a union declaration.

Type assertions

You can assert types in one of two ways

let value: any = 5;

let fixedString: string =  (<number>value).toFixed(4);
console.log(fixedString); // 5.0000

or

let fixedString: string =  (value as number).toFixed(4);

Functions

Adding types

With typescript we can specify types e.g.

function funFunc(score: number, message1: string = "default ", message2?: string): string {
   return message1 + message2;
}

The ? means the parameters is option and the final colon shows the return value of the function

Arrow Functions or lamdas

These take the format of

parameters  => function body

e.g. For zero parameters

 let greeting = () =>  console.log("Hello world");
 greeting(); // Hello world

For 1 parameter

 let squareit = x => x * x;
 let result = squareit(4); // 16

For multiple parameters

 let adder = (a,b) = a + b;
 let sum = adder(2,3); // 5

The example below shows a function on array (filter) which takes a function as an argument where the arguments are element, index and original array.

var scores = [70,125,85,110, 10000];

var highscores = scores.filter((element, index, array) => {
    var result = false
    if (index === 0) {
        console.log("arrrrayyy", array)
        result = true;
    }
	if(element > 100) {
  	    result = true;
    }
    return result;
});

console.log("test");
console.log("iain", highscores);

function types (delegates)

You can assign functions with the same signatures to variables with typescript. E.g.

function logError(err: string) : void {
   console.error(err);
}

function logLog(err: string) : void {
   console.log(err);
}

let logger : (value: string) => void;

if(x === 1)
{
  logger = logError;
}
else
{
  logger = logLog;
}

logger('Score: ${x}');

Custom types

Typescript supports classes and interfaces

Interfaces

interface Employee {
  name: string;
  title: string;
}

interface Manager extends Employee {
  department : string;
  numberOfEmployees: number;

  scheduleMeeting: (topic: string) => void;
}

let developer = {
  name: 'iain',
  title: 'GDB',
  editor: 'Visual Studio Code'
}

let newEmployee: Employee = developer;

Classes

Example below, default access is public

class Developer {

  department: string;
  private _title: string;
  
  get title(): string {
    return this._title;
  }

  set title(newTitle: string) {
    this._title = newTitle.toUppperCase();
  }

  // Static members and attributes exist
  static could_be_a_const: string = 'Hello me';
  static logMe() {
      console.log('Hello');
  }
}

// Extending
class WebDeveloper extends Developer {

   readonly favoriteEditor: string
   constructor(editor: string) {
      super();
      this.favoriteEditor = editor;
   }
}

Importing

To import typescript classes you can use the Triple-slash directive

/// <reference path="player.ts" />

TypeScript Declaration Files

These are typescript wrappers for JavaScript libraries. This allows the typescript compiler to validate your usage.

These will have the extension .d.ts and you can find these on GitHub at definitely typed. Note these may sometimes be out of date.

Search here

npm allows you to install these using

npm install --save @types/lodash