当前位置:网站首页>Typescript learning (I) type

Typescript learning (I) type

2022-06-26 12:33:00 Edison Dont

List of articles

Preface

One 、 Type declaration

Two 、 type

1.number

2.string

3.boolean

4. Literal

5. Joint type

6.any

7.unknown

8.void

9.never

10.object

11.array

12.tuple

13. enumeration enum

14. other


Preface

TypeScript Study notes Part 1 , About TS Type declaration and basic types .


One 、 Type declaration

  • Type declaration
    • The type declaration is TS A very important feature
    • Type declarations allow you to specify TS Medium variable ( Parameters 、 Shape parameter ) The type of
    • After specifying the type , When assigning a value to a variable ,TS The compiler will automatically check whether the value conforms to the type declaration , If yes, the value is assigned , Otherwise, the report will be wrong
    • In short , The type declaration sets the type... For the variable , So that variables can only store certain types of values
    • grammar :
      • let  Variable :  type ;
        
        let  Variable :  type  =  value ;
        
        function fn( Parameters :  type ,  Parameters :  type ):  type {
            ...
        }

  •   Automatic type determination
    • TS Have automatic type judgment mechanism
    • When the declaration and assignment of variables are carried out at the same time ,TS The compiler automatically determines the type of the variable
    • So if the variable is declared and assigned at the same time , You can omit the type declaration
      • // First declare the type and then assign the value 
        let a: string;
        a = 'Hello';
        
        // Declare types and assign values 
        let b: number = 123;
        
        // Declare variables and assign values at the same time 
        let c = false; 
        c = true; // The compiler automatically determines variables c by boolean

Two 、 type

type Example describe

number

1,-33, 2.5 Arbitrary number
string'hi', "HI" Any string
booleantrue,false Boolean value true or false
Literal Its own The value of the limiting variable is the literal value
any* Any type
unknown* Type safe any
void Null value (undefined) No value ( or undefined)
never No value Cannot be any value
object{name: "Alice"} Any of the JS object
array[1, 2, 3] arbitrarily JS Array
tuple[4, 5] Elements ,TS New type , Fixed length array
enumenum{A, B} enumeration ,TS New type in

1.number

let a: number;

a = 10;
a = 33;
//a = 'hello';  Variable a The type is number,  Cannot assign string 

2.string

let b: string;

b = 'hello';
//b = 123;  Variable b The type of is string ,  Can't assign a value number

3.boolean

let c: boolean;

c = true;

 4. Literal

let d: 10; //  here d It can only be equal to 10

//let d = 11;  May be an error , This limits the variable to the literal value ( Sort of like a constant )

 5. Joint type

let A: boolean | string; //  Variable A It can be either Boolean or string type 

A = true;
A = "Hello";
A = false;
A = "World";


//  Literal union type limit variable B Can only be "male" or "female"
let B: "male" | "female";
B = "male";
B = "female";
// B = "trans"  error 

 6.any

  Any type , It's like shutting down TS Restrictions on types ( Try not to use ).

let a: any;
a = true;
a = "hi";
a = 123;

//  If the declared variable does not specify a type , be TS The parser will automatically determine that the type of the variable is any
let b;
b = true;
b = "hi";
b = 123;

  Be careful any A variable of type can be assigned to any variable , Be prone to problems .

// any  Any type , It's like shutting down ts Restrictions on types ( Try not to use )
let B: any;
B = 10;
B = 'string';
B = true;

let S: string;
S = B; // any Types can be assigned to variables of any type , Be prone to problems .

 7.unknown

  Type safe any, Cannot be assigned directly to other variables .

let a: unknown;
a = 10;
a = "string";
a = true;

let b: string;
// b = a;  The compiler will report an error during assignment , Can't be “unknown” Type assigned to “string”.

    If you must assign a value , You can type before assignment or use assertions .

let a: unknown;
a = 10;
a = true;
a = "string";

let b: string;

/*
*   Assertion :
*    1.  Variable  as  type 
*    2. < type >  Variable 
*/

b = a as string;
b = <string> a;

/*
*   Type judgment before assignment 
*/

if (typeof c === 'string'){
    b = a;
}

 8.void

  no return value => It returns a null value / undefined

function foo(): void {
}

console.log(typeof foo()); // => undefined

function foo1(): void{
    return undefined;
}

function foo3(){
    //  Don't write void The default is void
}

//  Write the return value but not the return value type  =>  Automatically determine the return value type 
function foo4(){
    return 1;
}

console.log(typeof foo4()); // => number

 9.never

  No value , Cannot be any value ( even undefined None )

function foo(): never{
    throw new Error('raise');
}

 10.object

let o: {name: string, age: number};
o = {
    name: "Edison",
    age: 25
}

//  Define optional parameters 
// [propName: string]: any  Any type of attribute 
let a: {name: string, [propName: string]: any};
b = {
    name: 'Edison',
    age: 24,
    gender: "female"
}

//  Define the function structure 
let foo: (a: number, b: number) => number;
foo = function (n1, n2) {
    return n1 + n2;
}

11.array

/*
*   Declaration of arrays :
*    1.  type  []
*    2. Array < type >
*/

let a = number[];
a = [1, 2, 3];

let b = Array<number>;
b = [4, 5, 6];

12.tuple

/*
*   Tuples :  The length, type, and order must correspond to the storage elements one by one 
*    [ type , type ]
*/

let a = [string, number];
a = ["hello", 123];

// The following is an error 
a = [123, "hello"];
a = [123];
a = ["hello"];
a = ["hello", 123, 456];

13. enumeration enum

enum Gender {
    Male = 0,
    Female = 1
}

let person: {name: string, gender: Gender};
person = {
    name: "Edison",
    gender: Gender.Male
}

14. other

// &  At the same time satisfy 
let i: {name: string} & {age: number} & {gender: Gender};
i = person;
// i = b; Error 

//  Type the alias 
type myType = typeof i;
let person1: myType;
let person2: myType;
原网站

版权声明
本文为[Edison Dont]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202170515459339.html