This is the second day of my participation in the August More Text Challenge

ts

Basic usage

let a:number = 123
let b:string = 'a'
let c:boolean = true
let d:undefined = undefined 
Copy the code

literal

let c: boolean | string;
c = true;
c = "aa";
Copy the code
let c: "male" | "female";
c = "male";
c = "female";
Copy the code

Ts does not detect variables with any, just like js. It can be assigned to any type of variable

Unknown, the type is different, and an error will be reported after the assignment

object

Basic usage

let a: { name: string };
a = { name: "aa" };
Copy the code

Optional type

let a: { name: string; age? :number };
a = { name: "aa".age: 18 };
Copy the code

You can optionally add attributes of a fixed type in addition to mandatory attributes

let d: { name: string; [propsName: string] :any };
d = { name: "aa".bc: 12 };
Copy the code

array

String [] represents an array of strings

let e: string[];
e = ["a"."b"];
Copy the code

Or use

let e = Array<number>
Copy the code

Progenitor = a fixed-length array

let f: [string.string]
b = ['a'.'b']
Copy the code

Enum Enumerates all possibilities

enum Gender {
	male = 1,
	famale = 0,}let i: { name: string; gender: Gender } = { name: "aa".gender: Gender.famale };
Copy the code

Classes and objects

In classes and objects, we can split them into modules for type annotation. We can use the following form to export a class exported to annotate A in LabelledValue

export class aobj = {a:string;
  b:number;
}
interface LabelledValue {
  label: string;
  a:a obj;
}
Copy the code

Generally, in projects, the d.ts file class is used for type constraints on interfaces, mostly in the form of the above interface

The generic

Normal use

function f1<T.K> (number: T, str: K) :T {
    console.log(str)
    return number
}

f1<number.string> (10.'a')
Copy the code

Specifies that there are specific methods

interface Inter {
    length: number
}
// T must be an implementation class of Inter
function f2<T extends Inter> (a: T) :number {
    return a.length
}
f2('bbbb')
Copy the code

Generics, you can think of it as a variable, so if you pass in a T variable, you want to output a T variable as well, but you don’t have to pass in a number, a string, which is a fixed type, you can use generics.

Compile options (partial)

tsconfig.json

include
{
 "include": ["./src/**/*"]}Copy the code

Any file that contains any directory in the SRC folder under the current directory => will be compiled

exclude
{
  "include": ["./src/a/b"]}Copy the code

Indicates that a file is ignored

files
{
  "files": ["./src/a/b"]}Copy the code

Specify the files to include