TypeScript really fragrant Series - Basic type and variable declarations

Foreword

Content TypeScript really fragrant series of reference Chinese documents , but an example of the basic text of the document will not repeat the example, for some places will be in-depth study. In addition, the results of this paper are some examples of errors in the code is not compiled into JavaScript get. If you want to actually look at TypeScript compiled into JavaScript code, you can access TypeScript of online compilation addresses , hands-on, more impressive.

basic type

Boolean value

TypeScript and JavaScript, this is the most simple data types boolean, that is, true and false.

let isDone: boolean = false;

digital

TypeScript and JavaScript, like, TypeScript where all numbers are floating point type number. And ES6 as in, TypeScript supports decimal, hexadecimal, octal and binary literals.

let decLiteral: number = 6;
let hexLiteral: number = 0xf00d;
let binaryLiteral: number = 0b1010;
let octalLiteral: number = 0o744;

String

We can use string to represent the string, we can use several ways to represent.

let name: string = "bob"; //双引号
let friend: string = 'LeBron'; //单引号

let boy: string = `Hello, my name is ${name}, my friend is ${friend}.`;  //模板字符串
let man: string = "Hello, my name is" + name + " , my friend is" + friend + ".";  //字符串拼接

Array

There are two ways array definition.
1, after the element can be connected Type [], thus represents an array of type elements:

let list: number[] = [1, 2, 3];
let listStr: string[] = ["奥", "利", "给"];

2, the use of a generic array, Array <element type>:

let list: Array<number> = [1, 2, 3];
let listStr: Array<string> = ["奥", "利", "给"];

Tuple Tuple

Type allows a tuple represents the number of elements and the array of known type, not necessarily the same type of elements.

let x: [string, number];
x = ['hello', 10]; // OK
x = [10, 'hello']; // Error


//访问已知索引的元素,会得到正确的类型
console.log(x[0].substr(1)); // OK
console.log(x[1].substr(1)); // Error, 'number' does not have 'substr'

//访问一个越界的元素,会使用联合类型替代
x[3] = 'world'; // OK, 字符串可以赋值给(string | number)类型
console.log(x[5].toString()); // OK, 'string' 和 'number' 都有 toString
x[6] = true; // Error, 布尔不是(string | number)类型

Point to note here: since TyeScript 3.1 version, access to cross-border element will complain, we should no longer use this feature.

enumerate

Enumeration enum type is a standard JavaScript data type of supplement. Use an enumerated type can give a friendly name for a set of values.

enum Color {Red, Green, Blue}
let c: Color = Color.Green;

In the case of default, it is zero for the number of elements, of course, we can also manually specify the value of the members.

enum Color {Red = 1, Green, Blue}
let c: Color = Color.Green;

Any

To our "anyscript" (laugh), and if you do not specify the type of word is that default is any.

let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // ok

Although anyscript is a laugh, but any type is very useful, we can selectively include or remove the type checking at compile time. Sometimes, we want to specify a type for those in the programming phase unclear variable of type. These values ​​may come from dynamic content, such as input from a user or third party code libraries. In this case, we do not want the type checker to check these values, but direct them through the compilation phase checks.

//数组中元素的数据类型不一样的情况
let list: any[] = [1, true, "free"]; //ok

//如果数据类型定死的话,就会出错
let list: number[] = [1, true, "free"]; // error

Void

to a certain degree. any void and the opposite surface are represented as no type. When a function returns no value:

function warnUser(): void {
    console.log("奥利给");
}

We can only declare variables: undefined and null.

let unusable: void = undefined;

But sometimes may happen:

let unusable: void = null; //Type 'null' is not assignable to type 'void'.

This is because tsconfig.json is true in the strict caused.

Null 和 Undefined

By default, null and undefined are all types of sub-type, which means that can be assigned to other types.

let u: undefined = undefined;
let n: null = null;

However, when we specify -strictNullChecks mark, null and void and undefined only be assigned to each of them.

Never

never type represents the type of value that will never exist. never be any type of type subtype, may be assigned to any type; however, there never is a subtype of the type or types can be assigned to never (except never itself). Even if any can not be assigned to never.

// 返回never的函数必须存在无法达到的终点
function error(message: string): never {
    throw new Error(message);
}

// 推断的返回值类型为never
function fail() {
    return error("Something failed");
}

// 返回never的函数必须存在无法达到的终点
function infiniteLoop(): never {
    while (true) {
    }
}

Object

It represents a non-object primitive types, i.e. types except number, string, boolean, symbol, null or undefined in.

Type assertion

Assertion type (Type Assertion) may be used to specify the type of a value manually. That is, subjectively think what type of the variable Yes. It does not affect the running, but play a role in the compilation stage. The syntax is as follows:

// <类型>值
let someValue: any = "this is a string";

let strLength: number = (<string>someValue).length;


// 值 as 类型
let someValue: any = "this is a string";

let strLength: number = (someValue as string).length;

When we use the JSX in TypeScript, only as assertion syntax is allowed.

//需要在还不确定类型的时候就访问其中一个类型的属性或方法
function getLength(something: string | number): number {
    if (something.length) {
        return something.length;
    } else {
        return something.toString().length;
    }
}          //报错

//使用类型断
function getLength(something: string | number): number {
    if ((<string>something).length) {
        return (<string>something).length;
    } else {
        return something.toString().length;
    }
}

Variable declaration

Definition method

TypeScript way to declare variables and JavaScript is the same: var, let, const. As long as an understanding of JavaScript, then used in TypeScript problem is not big.

var a:number = 10;
let b:boolean = true;
const C:string = "10";

TypeScript JavaScript in some relatively specific wording:

let d:number|string = 10; // 用“|”表示这个变量可以为数字也可以为字符串

reference

https://github.com/zhongsp/TypeScript

At last

In some places the text may be added some of their own understanding, if not inaccurate or wrong place, welcome that -

Released four original articles · won praise 4 · Views 105

Guess you like

Origin blog.csdn.net/qq_42002487/article/details/104065109