当前位置:网站首页>Typescript (3) -- basic type syntax

Typescript (3) -- basic type syntax

2020-12-06 20:01:43 Naughty snow fox

Catalog

  • Basic type grammar

    • The original type

      • character string
      • Numbers
      • Boolean value
      • Null
      • Undefined
      • Symbol
    • Void
    • Never
    • any type
    • Object type
    • An array type
    • A tuple type

      • The use of tuples
    • Enumeration type

      • characteristic
      • DEMO
      • Enumerating types can invade code
      • Constant enumeration
  • TypeScript Study maps

Basic type grammar

The original type

character string
const a: string = 'foobar'
Numbers
const b: number = 100 // NaN 、 Infinity
Boolean value
const c: boolean = true // false
Null
const e: null = null

Non strict mode string、number、boolean、void Allow null null, Not in strict mode

//  Error will be reported in strict mode 
const d: string = null

How to turn off strict mode ? Find in the file strict

{
  "compilerOptions": {
    // true It's to turn on strict mode ,false Is to turn off strict mode 
    "strict": false,
  }
}
Undefined
const f: undefined = undefined
Symbol

Although it's a primitive type , But this type is ES6 Proposed , The default configuration is ES3, So there's an error .

If target Change to es5,Symbol You will also report mistakes. , What shall I do? ? TypeScript( One ) —— There are detailed descriptions in the type standard library

const h: symbol = Symbol()

Void

It means there is no type .

const d: void = undefined

When a function has no return value , You will usually see that the return value type is void.

function Fuc(): void {
    console.log('hello world')
}

Never

At present, there is no useful , Look at the document and say that function throw exception will use , So there's no explanation here .

any type

any It's any type , It's still a dynamic type , And ordinary JavaScript The variables are the same , You can store any type of value , It can also be changed to any type of value during operation , There are no mistakes in grammar , Because it's any type of value, so TypeScript It's not type checked .

let foo: any = 'string'

foo = 100

foo.bar()
//  At present value Can be any type of value 
function stringify(value: any) {
    return JSON.stringify(value)
}

stringify('string')
stringify(100)
stringify(true)

And it's because any No type checking , So there is still the problem of type safety , So don't use it easily , Its existence is still the main For the compatibility of old code .

Object type

Object A type is a non primitive type , Not just object types , It also includes objects 、 Array 、 Function type .

//  Using the original type will report an error 
//  here object Not just receiving objects , It includes functions 、 Arrays and objects 
const foo: object = function () {} //  object  {} //  Array  []

To simply define the literal form of an object type , The limitation is that the structure of the assigned object must be exactly the same as that defined , No more, no less .

const obj: {foo: number, bar: string} = {foo: 123, bar: 'string'}

If in TypeScript Object types are restricted in , A more professional way is to use interfaces , The interface will be discussed next time .

An array type

//  General statement 
const arr1: Array<number> = [1, 2, 3]
//  A short statement 
const arr2: number[] = [1, 2, 3]

for instance : The parameter that passes in the number , Finally, the sum of the numbers is returned

//  So here's to make sure that we have a numeric type here , Add array type annotation 
function sum (...args: number[]) {
  // reduce The first parameter of is the result of the last callback   The second parameter is the current value ( The initial value is 0), Finally, I return to the sum of the two 
  return  args.reduce((prev, current) => prev + current, 0)
}

console.log(sum(1, 2, 3, 4, 5)) // 15
console.log(sum(1, 2, '3', 4, 5)) // error!

A tuple type

Tuples are explicit numbers of elements , And an array of each element type . Array literals can be used to declare tuple types .

//  If the type and quantity of the following do not match, an error will be reported 
const tuple: [number, string] = [1, 'string']

//  If you want to access the elements of a tuple , You can still access it by subscript 
const age = tuple[0]
const name = tuple[1]

//  You can also use array deconstruction to access 
const [age, name] = tuple
The use of tuples
  1. Return multiple return values in a function
  2. React useState() Hook Return tuple type
  3. Object.entries() Get the array of all the key values in the object , Each key value is a tuple

Enumeration type

Development process , It often involves the need to use a certain number of values to represent certain states . This data structure is very common in other languages , But in JS There is no such data structure in , You usually use objects to simulate .

const PostStatus = {
    Draft: 0,
    Unpublished: 1,
    Published: 2
}

const page = {
    title: 'typeScript guide ',
    content: 'content',
    status: PostStatus.Draft
}
characteristic

Now? TypeScript There are enumeration types in , Its characteristics are :

  1. Give a group of values a more semantic name
  2. There are only a few fixed values in a set of data , There is no possibility of going beyond the scope
DEMO

for instance : Here are the three states of publishing books :

  • Draft It's draft status :0
  • Unpublished It's unpublished :1
  • Published It has been published :2
// enum Is enumeration type , After that is the enumeration name , It uses an equal sign, not a colon 
enum PostStatus {
  Draft = 0,
  Unpublished = 1,
  Published = 2
}
//  When you use it, you still use the object . The way to use 
const post = {
  title: 'typeScript guide ',
  content: 'content',
  status: PostStatus.Published // 1 // 0
}

If not =, Then the value will default from 0 Start accumulating

enum PostStatus1 {
  Draft, // 0
  Unpublished, // 1
  Published // 2
}

If you give the first value , Then the members will accumulate on this basis

enum PostStatus2 {
  Draft = 6, // 6
  Unpublished, // 7
  Published // 8
}

The value of an enumeration can also be a string , String cannot grow by itself , Each needs to be assigned a value

enum PostStatusStr {
  Draft = 'string1',
  Unpublished = 'string2',
  Published = 'string3'
}
Enumerating types can invade code

Enumeration types can invade the runtime code , In short, it will affect the compilation results ,TypeScript Most of the types will eventually be removed by compilation , Just for type checking during development , And the enumeration compiles into Two way key value pair object , You can find the key by value , You can find the value according to the key .

The following code will be retained in the project

var PostStatus;
(function (PostStatus) {
    //  You can see the following code , The inner layer uses the key of enumeration to store the value of enumeration , The outer layer uses the value of the enumeration to make the key , Save the keys for enumeration 
    PostStatus[PostStatus["Draft"] = 0] = "Draft";
    PostStatus[PostStatus["Unpublished"] = 1] = "Unpublished";
    PostStatus[PostStatus["Published"] = 2] = "Published";
})(PostStatus || (PostStatus = {}));

The purpose of this is : The name of the enumeration can be obtained dynamically according to the enumeration value

PostStatus[0] // Draft

If we don't use the above statement to access the key , Then it is recommended to use Constant enumeration

Constant enumeration

Constant enumeration is in enum Add const, So you don't invade the code , The code for the above two-way key value pair will be removed , Just add some comments at the end .

  • No addition const After compiling the code
var PostStatus;
(function (PostStatus) {
    PostStatus[PostStatus["Draft"] = 0] = "Draft";
    PostStatus[PostStatus["Unpublished"] = 1] = "Unpublished";
    PostStatus[PostStatus["Published"] = 2] = "Published";
})(PostStatus || (PostStatus = {}));

var post = {
    title: 'Hello TypeScript',
    content: 'content',
    status: PostStatus.Published // 1 // 0
};
  • Add const After compiling the code
//  above PostStatus Will take out , Change it to the following value 
var post = {
    title: 'Hello TypeScript',
    content: 'content',
    status: 2 /* Published */ // 1 // 0
};

TypeScript Study maps

版权声明
本文为[Naughty snow fox]所创,转载请带上原文链接,感谢
https://chowdera.com/2020/12/20201206195929857t.html