Skip to main content

Basic Types_TypeScript Notes 2

Free2019-01-12#TypeScript#TypeScript变量类型#TypeScript教程#TypeScript数组类型#TypeScript修改window#TypeScript修改global

13 basic types

1. JavaScript Types

JavaScript has 7 types: Boolean, Number, String, Undefined, Null, Object, and ES6's newly added [Symbol](/articles/symbol-es6 笔记 7/)

TypeScript supports all 7 of these:

// JavaScript 支持的 7 种类型
let isDone: boolean = false;  // 布尔值
let decimal: number = 6;      // 数值
let color: string = 'blue';   // 字符串
let u: undefined = undefined; // Undefined
let n: null = null;           // Null
let obj: object = {};         // Object
let sym: symbol = Symbol();   // Symbol

Variable Declarations

Variables in above examples are all declared through let, actually there are 3 variable declaration methods:

  • var: Function scope

  • let: Block scope

  • const: Block scope, constant (not allowed to modify)

For example:

var a: string = 'a';
let b: string = 'b';
const c: string = 'c';

Completely consistent with JavaScript variable declaration methods, no need to elaborate, specifically see Variable Declarations

P.S. Actually, let and const will eventually be compiled to var, block scope and other features are simulated through variable renaming

2. TypeScript Types

TypeScript has total 13 basic types, besides all 7 from JavaScript, also has:

  • Array: Array, represents a group of elements of same type

  • Tuple: Tuple, represents a group of fixed number of elements (doesn't require element types to be same), such as binary tuple, ternary tuple

  • Enum: Enumeration, constant collection

  • Any: Any type, represents unknown type, such as dynamic content (user input, or third-party libraries) or things of unknown type (mixed type arrays), can declare any type to bypass type checking

  • Void: Void type, represents no type, such as return value type of functions without return value

  • Never: Type of values that never exist, such as return value type of functions that never return (must throw exception, or function body has infinite loop)

Examples as follows:

// TypeScript 新增的 6 种类型
let list: number[] = [1, 2, 3];       // 数组
let list: Array<number> = [1, 2, 3];  // 数组
let x: [string, number] = ["hello", 10];        // 元组
enum Color {Red = 'r', Green = 'g', Blue = 'b'} // 枚举
let notSure: any = 4;                 // 任意类型
let list: any[] = [1, true, "free"];  // 任意类型数组(未知类型)
function warnUser(): void {/*..*/}              // 空类型
function neverReturn(): never {throw 'error';}  // 绝不存在的类型

Need to note several points:

  • Array type has 2 declaration formats (elemType [] and Array<elemType>)

  • When accessing Tuple out of bounds, applies union type, so x[10] in above example has type string | number

  • Enum values can be omitted, defaults to start from 0 according to key declaration order. If numeric value is specified, next item's value increments on this basis, otherwise requires subsequent items to all specify values (default numeric increment mechanism can't handle it)

  • Any type is equivalent to local type checking switch, this is very meaningful in projects where TypeScript and JavaScript code coexist

  • Void type variables are also legal, constrains values can only be undefined or null

  • Null, Undefined and Never are subtypes of other types, therefore can be assigned to any other type variables (for example let str: string = null is also legal)

  • Any other types cannot be assigned to Never type, even Any doesn't work

  • Never type variables are also legal, at this point Never can be used as type guard (for example declare const name: never; avoids implicitly accessing window.name)

P.S. Specially, suggest enabling --strictNullChecks option, at this point Undefined and Null only allowed to assign to Void and their respective corresponding types

P.S. About Never's application as type guard, see Improve type safety of name global variable

3. Type Assertions

Can inform TypeScript compiler of exact type of certain value through type assertions:

Type assertions are a way to tell the compiler "trust me, I know what I'm doing."

Similar to type casting in other languages, difference is type assertions are only at compile time, doesn't have runtime impact like type conversion:

A type assertion is like a type cast in other languages, but performs no special checking or restructuring of data. It has no runtime impact, and is used purely by the compiler.

Has two syntax formats,分别是 <type> and as type, for example

let someValue: any = "this is a string";
// <type>
let strLength: number = (<string>someValue).length;
// as type
let strLength: number = (someValue as string).length;

Two methods are equivalent, but in JSX can only use as type (angle bracket syntax conflicts with JSX syntax)

4. Common Techniques

Accessing Enum Keys

Actually, TypeScript enum types establish key-value bidirectional index, for example:

enum Color {Red = 1, Green, Blue}
// 对应的 JavaScript 为
var Color;
(function (Color) {
    Color[Color["Red"] = 1] = "Red";
    Color[Color["Green"] = 2] = "Green";
    Color[Color["Blue"] = 3] = "Blue";
})(Color || (Color = {}));
// 得到
// {1: "Red", 2: "Green", 3: "Blue", Red: 1, Green: 2, Blue: 3}

Therefore, an interesting technique is accessing key according to enum value:

let colorName: string = Color[2];
// 此时,colorName 为'Green'

Modifying global

Any type is used to bypass compile-time type checking, therefore can be used to modify some things that can't be modified, for example:

window.customFunction = myCustomFunction;

Compile error:

Property 'customFunction' does not exist on type 'Window'.

Can bypass through any type:

const globalAny: any = window;
globalAny.customFunction = myCustomFunction;

Or equivalent type assertion:

(<any> window).customFunction = myCustomFunction;
// 或
(window as any).customFunction = myCustomFunction;

Reference Materials

Comments

No comments yet. Be the first to share your thoughts.

Leave a comment