JavaScript comes in two types: Primitive data types and Object types.
Primitive data types include: values, strings, booleans, null, undefined, and the new types Symbol and BigInt in ES6.
Value –Number
Like JavaScript, all numbers in TypeScript are floating point numbers. In addition to supporting decimal and hexadecimal literals, TypeScript also supports binary and octal literals introduced in ES6.
let decLiteral: number = 6; let hexLiteral: number = 0xf00d; let binaryLiteral: number = 0b1010; // let octalLiteral: number = 0o744; // octal let notANumber: number = NaN; let infinityNumber: number = Infinity;Copy the code
The compiled:
var decLiteral = 6; var hexLiteral = 0xf00d; var binaryLiteral = 10; Var octalLiteral = 484; // octal var notANumber = NaN; var infinityNumber = Infinity;Copy the code
Binary and octal in ES6 are compiled to decimal.
String –String
Use string to define a string type:
let myName: string = 'www'; let myAge: number = 18; String = 'Hello, my name is ${myName}. I'll be ${myAge + 1} years old next month.';Copy the code
The compiled:
var myName = 'www'; var myAge = 18; Var sentence = "Hello, my name is "+ myName + ". I'll be" + myAge + 1 + "years old next month.";Copy the code
Boolean value –Boolean
The most basic data types are simple true/false values, called Boolean in JavaScript and TypeScript.
let isDone: boolean = false;
Copy the code
New Boolean() returns a Boolean object:
let createdByNewBoolean: Boolean = new Boolean(1);
Copy the code
A direct call to Boolean can also return a Boolean type:
let createdByBoolean: boolean = Boolean(1);
Copy the code
In TypeScript, Boolean is the basic type in JavaScript, and Boolean is the constructor in JavaScript.
A null value –Void
In a way, void is like the opposite of any; it means there is no type at all. When a function returns no value, you usually see the return type void:
function warnUser(): void {
console.log("This is my warning message");
}
Copy the code
Declaring a void variable doesn’t do much good, because you can only assign undefined and null to it:
let unusable: void = undefined;
Copy the code
Null, and Undefined
In TypeScript, undefined and null have their own types called undefined and NULL, respectively. Like void, their own types are not very useful:
let u: undefined = undefined;
let n: null = null;
Copy the code
By default null and undefined are subtypes of all types. This means that you can assign null and undefined to variables of type number.
let num: number = undefined;
Copy the code
Void variables cannot be assigned to variables of type number:
let u: void;
let num: number = u;
// Type 'void' is not assignable to type 'number'.
Copy the code
Never
The never type represents the types of values that never exist. For example, the never type is the return type of function expressions or arrow function expressions that always throw an exception or have no return value at all.
The never type is a subtype of any type and can be assigned to any type; However, no type is a subtype of never or can be assigned to a type of never (except never itself). Even any cannot be assigned to never.
Function error(message: string): never {throw new error(message); } // The inferred return value type is never function fail() {return error("Something failed"); Function infiniteLoop(): never {while (true) {}}Copy the code
A tuple –Tuple
The tuple type allows you to represent an array with a known number and type of elements that need not be of the same type.
For example, define a pair of tuples with values of string and number:
let x: [string, number];
x = ['1', 1] // OK
x = [1, 1] // Error
x = ['1', 1, 2] // Error
Copy the code
When assigning or accessing an element with a known index, the correct type is obtained:
console.log(x[0].substr(1)); // OK
console.log(x[1].substr(1)); // Error, 'number' does not have 'substr'
Copy the code
When an out-of-bounds element is added, its type is limited to the combined type of each type in the tuple:
x.push(1); // OK
x.push('123'); // OK
x.push(true); // Error
Copy the code
Enumeration –Enum
The enumeration (Enum) type is used in scenarios where values are limited. For example, up, down, left, right, seven days a week, twelve months a year.
Enumerations are defined using the enum keyword. Enumerators are assigned an increasing number starting from 0, and the enumerator values are mapped backwards to the enumerator name:
enum Days {Sun, Mon, Tue, Wed, Thu, Fri, Sat};
console.log(Days["Sun"] === 0); // true
console.log(Days[0] === "Sun"); // true
Copy the code
In fact, the above example would compile to:
var Days;
(function (Days) {
Days[Days["Sun"] = 0] = "Sun";
Days[Days["Mon"] = 1] = "Mon";
Days[Days["Tue"] = 2] = "Tue";
Days[Days["Wed"] = 3] = "Wed";
Days[Days["Thu"] = 4] = "Thu";
Days[Days["Fri"] = 5] = "Fri";
Days[Days["Sat"] = 6] = "Sat";
})(Days || (Days = {}));
Copy the code
Manual assignment
We can also assign enumerations manually:
enum Days {Sun = 7, Mon = 1, Tue, Wed, Thu, Fri, Sat};
console.log(Days["Sun"] === 7); // true
console.log(Days["Mon"] === 1); // true
console.log(Days["Tue"] === 2); // true
console.log(Days["Sat"] === 6); // true
Copy the code
In the above example, enumerators that are not manually assigned are incremented after the previous enumerator.
Enum Days {Sun = 7, Mon = 1.5, Tue, Wed, Thu, Fri, Sat}; console.log(Days["Sun"] === 7); // true console.log(Days["Mon"] === 1.5); // true console.log(Days["Tue"] === 2.5); // true console.log(Days["Sat"] === 6.5); // trueCopy the code
Digital enumeration
Constant enumerations are enumerations defined using const enum:
enum Directions { Up = 1, Down, Left, Right } const dir = [Directions.Up, Directions.Down, Directions.Left, Directions.Right]; var dir = [1, 2, 3, 4]; / / the compiledCopy the code
If a calculated member is included, an error is reported at compile time:
const enum Color {Red, Green, Blue = "blue".length};
// index.ts(1,38): error TS2474: In 'const' enum declarations member initializer must be constant expression.
Copy the code
Any
Sometimes we want to specify a type for variables whose type is not known at programming time. These values may come from dynamic content, such as user input or third-party code libraries. In this case, the type can be defined as Any. An arbitrary value (Any) is used to indicate that assignments of Any type are allowed.
If it is a common type, it is not allowed to change the type during assignment:
let myValue: string = 'wwx';
myValue = 30;
// index.ts(2,1): error TS2322: Type 'number' is not assignable to type 'string'.
Copy the code
However, if it is of any type, it is allowed to be assigned to any type.
let myValue: any = 'wwx';
myValue = 30;
Copy the code
A variable is recognized as any value type if its type is not specified when it is declared:
let something;
something = 'wwx';
something = 30;
something.setName('Tom');
Copy the code
Is equivalent to:
let something: any;
something = 'wwx';
something = 30;
something.setName('Tom');
Copy the code
The any type is also useful when you only know part of the data type. For example, you have an array that contains different types of data:
let list: any[] = [1, true, "free"];
list[1] = 100;
Copy the code
Properties and methods of arbitrary values
It is allowed to access any property on any value:
let anyThing: any = 'hello'
console.log(anyThing.myName)
console.log(anyThing.myName.firstName);
Copy the code
It also allows any method to be called:
let anyThing2: any = 'Tom';
anyThing2.setName('Jerry');
anyThing2.setName('Jerry').sayHello();
anyThing2.myName.setFirstName('Cat');
Copy the code
The above section is written without error, and the TS compilation will pass normally. This does not mean that the operation is error-free.
The joint type
Union Types indicate that the value can be one of many Types.
let value: string | number;
value = 'wwx'
value = 123;
Copy the code
Access a property or method of the union type
When TypeScript doesn’t know what type a variable of a union type is, we can only access properties or methods that are common to all types of the union type:
function getLength(something: string | number): number {
return something.length;
}
// index.ts(2,22): error TS2339: Property 'length' does not exist on type 'string | number'.
// Property 'length' does not exist on type 'number'.
Copy the code
In this example, length is not a common attribute of string and number, so an error is reported.
There is no problem accessing the common attributes of string and number:
function getString(something: string | number): string {
return something.toString();
}
Copy the code
When a variable of the union type is assigned, it can infer a type according to the rules of type inference:
let value: string | number; value = 'wwx'; console.log(value.length); // 3 value = 10; console.log(myFavoriteNumber.length); // Property 'length' does not exist on type 'number'.Copy the code
The second line value is inferred to be a string, so it has the length attribute. The fourth line is inferred to be a number and has no length attribute, so an error is reported.
reference
TypeScript Primer – ts.xcatliu.com/
TypeScript website – www.typescriptlang.org/