This is the 11th day of my participation in the August More Text Challenge
Literal type
This chapter takes a look at a special type Literal in TS (we can reference specific strings and numbers at type positions in addition to strings and numbers of the normal type) to achieve some nifty things.
constant
Consider an example of using a literal type to do something like a constant. This is an example of how it works.
let s: 'hw' = 'hw'
let n: 1 = 1;
Copy the code
In the above example: declare s as the string ‘hw’; The value of n is 1; It cannot be modified later.
But having a variable that can only have one value is not very useful, and it can be easily implemented using const
The joint type
We can express a more useful concept by grouping text into associative types
For example, a function that accepts only a specific set of known values
type a = -1 | 0 | 1
function compare(a: string, b: string) :a {
return a === b ? 0 : a > b ? 1 : -1;
}
Copy the code
In the example above, we assume we need a version comparison method called compare, which returns only 0,1, and -1.
Combined with the interface
We can also use it with interfaces:
interface f {
age: number;
}
type s = f | 'son'
function fn(x: s) { }
fn({ age: 100 });
fn("son");
Copy the code
In the above example, alias S has both the rules of interface F.
There is also a special type of text: Boolean. Boolean types There are only two Boolean literal types, true and false. This shows that the type Boolean itself is really just a union type in a literal type
application
Here is an example to show the application in a real project
We declare an HTTP request method and call it, as shown in the following example:
type obj = {
url: string;
method: "GET" | "POST"
}
function http(arg: obj) {}let params = { url: 'www.lsdj.sdf'.method: "GET" }
http(params)
Copy the code
//Type ‘string’ is not assignable to type ‘”GET” | “POST”‘.
Params: Method is a string, so TS helps me infer that method is a string. But we only accept the text in the encapsulation of the HTTP request method type “GET” | “POST”! If you want this code to work, you need to change the type of method in Params
let params = { url: 'www.lsdj.sdf'.method: "GET" as "GET" }
let params = { url: 'www.lsdj.sdf'.method: "GET" } as const
Copy the code
The above two ways can meet our needs
Object is constant
In addition to the readonly modifier, there are other ways to make values within an object unmodifiable
let obj = { a: 1} as const;
Copy the code
The as const suffix acts like const, but for the type system, ensure that all attributes are assigned to literal types, rather than more generic versions such as strings or numbers.