Typescript base types
Here are just a few special types that differ from JavaScript
The Tuple tuples
- 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, you can define a pair of tuples of type string and number.
// Declare a tuple type
let x: [string, number];
// Initialize it
x = ['hello'.10]; // OK
// Initialize it incorrectly
x = [10.'hello']; // Error
Copy the code
Extended union type
// Define an associative type when you have only number and string in your arraylet a =(number | string)[]
Copy the code
Enum enumeration
- Enum types complement the JavaScript standard data types. As with other languages such as C#, enumeration types can be used to give friendly names to a set of values.
enum Color {Red, Green, Blue}
let c: Color = Color.Green;
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;
Copy the code
// ts
enum types { //ok
primary, info, danger / / 0, 1, 2
}
//ts compiled js
var types;
(function (types) {
types[types["primary"] = 0] = "primary";
types[types["info"] = 1] = "info";
types[types["danger"] = 2] = "danger"; / / 0, 1, 2
})(types || (types = {}));
Copy the code
As you can see, we can access string values by 0, 1, and 2, or we can access them in the reverse direction. Here we have two-way access to the values.
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, we don’t want the type checker to check these values and just pass them through compile-time checks. We can then mark these variables with type any:
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean
Copy the code
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
- This is used for func, just the opposite of Any
function warnUser() :void {
console.log("This is my warning message");
}
// Declaring a void variable is useless 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
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; Variables can also be of type never, when they are bound by type protection that is never true.
// 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
Typescript generic
Let’s talk about usage scenarios
- To simulate a scenario, when we want to use different data provided by a server, we need to build a middleware for processing (validation, fault tolerance, correction) before using it. Write it in JavaScript.
JavaScript
// Simulate the service to provide different data. Here we simulate a string and a number
var service = {
getStringValue: function() {
return "a string value";
},
getNumberValue: function() {
return 20; }};// Middleware for processing data. Here, log is used to simulate processing, and the data is directly returned as the processed data
function middleware(value) {
console.log(value);
return value;
}
// JS does not care about types, so there is no problem here
var sValue = middleware(service.getStringValue());
var nValue = middleware(service.getNumberValue());
Copy the code
typeScript
- The type returned by the server is limited
const service = {
getStringValue(): string {
return "a string value";
},
getNumberValue(): number {
return 20; }};Copy the code
- To make sure that type checking works for sValue and nValue in subsequent operations, they will also have types (if the Middleware type is properly defined, it can be inferred, so let’s show that the type is defined).
const sValue: string = middleware(service.getStringValue());
const nValue: number = middleware(service.getNumberValue());
Copy the code
When switching to typescript, our middleware needs to return the correct string and number types. What do we need to do?
Method one, special type any
function middleware(value: any) :any{
console.log(value);
return value;
}
Copy the code
This will pass the final type check, but using any makes middleware useless.
Method two, multiplemiddleware
function middleware1(value: string) :string {... }function middleware2(value: number) :number {... }Copy the code
- Overload with typescript
function middleware(value: string) :string;
function middleware(value: number) :number;
function middleware(value: any) :any {
// The implementation also has no strict type checking
}
Copy the code
But this doesn’t work with too many types.
True: Using typescript Generic
- So let’s just talk briefly about what generics are.
- == is a variable representing a type, used instead of an actual type for programming purposes. = =
function middleware<T> (value: T) :T {
console.log(value);
return value;
}
Copy the code
Middleware is followed by
to declare a type variable, Value: T to declare a parameter of type T, and: T to declare a return Value of type T. Middlewre (getStringValue()) is called, so T stands for string, so the middleware return type is string. For the middleware(getNumberValue()) call, the T represents number.
- If you use
vscode
We default to the typescript-enabled environment you already have installed. You can see that when we derive the types and return value types,vscode
You’ll be promptedstring
和number
The type of.
Type overloading and type protection DEMO
The function on (event: string, (content: string | number) = > unkown) {} / / type of overloaded function on (the event: 'message' (content: string)){} functon on(evnet: 'close', (payload: number)){} const setType =new Set { message: string; close: number; Function on<T keyof setType>(event: T, payload: setType[T])){}Copy the code
Talk about Tslint configuration
- www.alloyteam.com/2017/08/130…