Welcome to wechat public account: Front Reading Room
TypeScript supports almost the same data types as JavaScript, and it also provides useful enumerated types for us to use.
Boolean value
The most basic data types are simple true/false values, called Boolean in JavaScript and TypeScript (and in other languages as well).
let isDone: boolean = false;
Copy the code
Number (number)
Like JavaScript, all numbers in TypeScript are floating point numbers. These floating point numbers are of type number. In addition to supporting decimal and hexadecimal literals, TypeScript also supports binary and octal literals introduced in ECMAScript 2015.
let decLiteral: number = 6;
let hexLiteral: number = 0xf00d;
let binaryLiteral: number = 0b1010;
let octalLiteral: number = 0o744;
Copy the code
string
As in other languages, we use string to represent the text data type.
let name: string = "bob";
Copy the code
An array of
There are two ways to define an array. First, the element type can be followed by [] to represent an array of elements of that type:
let list: number[] = [1.2.3];
Copy the code
The second way is to use Array generics, Array< element type > :
let list: Array<number> = [1.2.3];
Copy the code
Tuples 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.
// Declare a tuple type
let x: [string.number];
// Initialize it
x = ['hello'.10]; // OK
// Initialize it incorrectly
x = [10.'hello']; // Error
Copy the code
When accessing an out-of-bounds element, the union type is used instead:
x[3] = 'world'; / / OK, strings can be assigned to (string | number) type
console.log(x[5].toString()); // OK, 'string' and 'number' both have toString
x[6] = true; / / Error, Boolean not (string | number) type
Copy the code
The enumeration
Enum types complement the JavaScript standard data types. Enumeration types are used to give friendly names to a set of values.
enum Color {Red, Green, Blue}
let c: Color = Color.Red;/ / 0
Copy the code
By default, elements are numbered from 0. You can also manually specify the values of the members. For example, let’s change the above example to number from 1:
enum Color {Red = 1, Green, Blue}
let c: Color = Color.Green;/ / 2
Copy the code
You can find its name by enumeration of values. For example, if we know that the value is 2, but are not sure which name in Color it maps to, we can look for the corresponding name:
enum Color {Red = 1, Green, Blue}
let colorName: string = Color[2];
console.log(colorName); // Display 'Green' because its value is 2 in the code above
Copy the code
Any
Sometimes we want to specify a type for variables whose type is not known at programming time. Such as from user input or third-party code libraries. Then we can mark these variables with type any.
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean
Copy the code
Object has a similar effect. It allows you to assign arbitrary values – but you cannot call arbitrary methods on it, even if it does have them:
let notSure: any = 4;
notSure.ifItExists(); // okay, ifItExists might exist at runtime
notSure.toFixed(); // okay, toFixed exists (but the compiler doesn't check)
let prettySure: Object = 4;
prettySure.toFixed(); // Error: Property 'toFixed' doesn't exist on type 'Object'.
Copy the code
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:
// Not much else we can assign to these variables!
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.
However, when you specify strictNullChecks, null and undefined can only be assigned to void and their respective checks. This avoids many common problems.
Never
The never type represents the types of values that never exist. For example, the never type is the return type of functions that always throw an exception or return no value at all; Variables can also be of type never, when they are bound by type protection that is never true.
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.
Here are some functions that return type never:
// A function that returns never must have an unreachable end
function error(message: string) :never {
throw new Error(message);
}
// The inferred return value type is never
function fail() {
return error("Something failed");
}
// A function that returns never must have an unreachable end
function infiniteLoop() :never {
while (true) {}}Copy the code
Object
Object represents a non-primitive type, that is, a type other than number, string, Boolean, symbol, NULL, or undefined.
Use the object type to better represent apis like Object.create. Such as:
declare function create(o: object | null) :void;
create({ prop: 0 }); // OK
create(null); // OK
create(42); // Error
create("string"); // Error
create(false); // Error
create(undefined); // Error
Copy the code
Types of assertions
Sometimes you’ll find that you know more about a value than TypeScript does. Usually this happens when you clearly know that an entity has a more exact type than its existing type. This is where you can use type assertions.
Type assertion is like conversion in other languages, but without special data checking and deconstruction. It has no run-time impact, only at compile time. TypeScript assumes that you, the programmer, have done the necessary checks.
Type assertions come in two forms. The first is the Angle bracket syntax:
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
Copy the code
The other is the as syntax:
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
Copy the code
The two forms are equivalent. Which to use is mostly a matter of personal preference; But when you use JSX in TypeScript, only AS syntax assertions are allowed.
Welcome to wechat public account: Front Reading Room