当前位置:网站首页>Typescript learning (I) type
Typescript learning (I) type
2022-06-26 12:33:00 【Edison Dont】
List of articles
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 |
boolean | true,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 |
enum | enum{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;
边栏推荐
- 2022 China smart bathroom cabinet Market Research and investment Competitiveness Analysis Report
- 7-1 n皇后问题
- 请指教同花顺是什么软件?在线开户安全么?
- One click deployment CEPH script
- Ubuntu安装配置PostgreSQL(18.04)
- Is it safe to open a securities account in general
- PHP returns false when calling redis method decrby less than 0
- The loss of female scientists
- dried food! Yiwen will show you SD card, TF card and SIM card!
- 7-2 大盗阿福
猜你喜欢
Scala-day06- pattern matching - Generic
Ctrip ticket app KMM cross end kV repository mmkv kotlin | open source
[redis series] redis learning 16. Redis Dictionary (map) and its core coding structure
"Pinduoduo and short video speed version", how can I roast!
Microservice governance (nocas)
Php+laravel5.7 use Alibaba oss+ Alibaba media to process and upload image / video files
[solved] laravel completes the scheduled job task (delayed distribution task) [execute a user-defined task at a specified time]
Scala-day03- operators and loop control
PHP uses laravel pay component to quickly access wechat jsapi payment (wechat official account payment)
SQL injection in Pikachu shooting range
随机推荐
7-16 货币系统Ⅰ
2022 China smart bathroom cabinet Market Research and investment Competitiveness Analysis Report
Introduction to the four major FPGA manufacturers abroad
Laravel+gatewayworker completes the im instant messaging and file transfer functions (Chapter 4: server debugging errors)
Hello! Forward proxy!
VMware虚拟机 桥接模式 无法上网 校园网「建议收藏」
I want to know whether flush is a stock market? Is online account opening safe?
[graduation season · advanced technology Er] I remember the year after graduation
Oracle锁表查询和解锁方法
VMware virtual machine bridging mode can not access the campus network "suggestions collection"
PHP generate order number
Thinkphp5 query report: sqlstate[hy093]: invalid parameter number
Five problems and solutions of member operation
Current situation investigation and investment prospect forecast analysis report of China's electrolytic copper market from 2022 to 2028
24 database interview questions that must be mastered!
大智慧哪个开户更安全,更好点
Laravel subdomain accesses different routing files and different modules
redis通过6379端口无法连接服务器
国际美妆业巨头押注中国
一个初级多线程服务器模型