directory

  • Basic type syntax
    • The original type
      • string
      • digital
      • Boolean value
      • Null
      • Undefined
      • Symbol
    • Void
    • Never
    • Any type
    • The Object type
    • An array type
    • A tuple type
      • Usage scenarios of tuples
    • Enumerated type
      • The characteristics of
      • DEMO
      • Enumeration types invade code
      • Constant enumeration
  • TypeScript learns maps

Basic type syntax

The original type

string

const a: string = 'foobar'
Copy the code

digital

const b: number = 100 // NaN 、 Infinity
Copy the code

Boolean value

const c: boolean = true // false
Copy the code

Null

const e: null = null
Copy the code

String, number, Boolean, and void can be null in non-strict mode, but not in strict mode

// An error will be reported in strict mode
const d: string = null
Copy the code

How do I turn off strict mode? Find strict in the file

{
  "compilerOptions": {
    // True indicates that strict mode is enabled. False indicates that strict mode is disabled
    "strict": false,}}Copy the code

Undefined

const f: undefined = undefined
Copy the code

Symbol

Although it is a primitive type, this type is proposed by ES6, and the default configuration is ES3, so an error is reported.

If target is changed to ES5, Symbol will also fail. TypeScript(I) — The types standard library explains this in detail

const h: symbol = Symbol(a)Copy the code

Void

It means there is no type.

const d: void = undefined
Copy the code

When a function returns no value, you will usually see the return type void.

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

Never

The function throws an exception, so I will not explain it here.

Any type

Any is an arbitrary type, which is still dynamically typed, just like normal JavaScript variables. It can store any type of value and change to any type at run time. Syntactically, TypeScript does not type check any type of value.

let foo: any = 'string'

foo = 100

foo.bar()
Copy the code
// The current value can be any type of value
function stringify(value: any) {
    return JSON.stringify(value)
}

stringify('string')
stringify(100)
stringify(true)
Copy the code

Because any doesn’t do type checking, it still has type safety issues, so don’t use it lightly, and it’s still there primarily for compatibility with older code.

The Object type

The Object type is a non-primitive type. It not only refers to Object types, but also includes Object types, arrays, and function types.

// An error is reported using primitive types
// Object does not accept only objects, but includes functions, arrays, and objects
const foo: object = function () {} // object {} // array []
Copy the code

The constraint is that the assigned object structure must be exactly the same as defined, no more or less.

const obj: {foo: number, bar: string} = {foo: 123.bar: 'string'}
Copy the code

If you restrict object types in TypeScript, the more technical approach is to use interfaces, which we’ll talk about next time.

An array type

// Common declaration
const arr1: Array<number> = [1.2.3]
// Brief statement
const arr2: number[] = [1.2.3]
Copy the code

An example would be to pass in a number and return the sum of the numbers

// So we need to make sure we have a numeric type here, add an array type annotation
function sum (. args: number[]) {
  The first argument to reduce is the result of the previous callback and the second argument is the current value (starting at 0), and the sum of the two is returned
  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!
Copy the code

A tuple type

A tuple is an array that specifies the number of elements and the type of each element. Tuple types can be declared by array literals.

// If the following type and quantity are inconsistent, an error will be reported
const tuple: [number, string] = [1.'string']

// If you want to access elements of a tuple, use subscripts as usual
const age = tuple[0]
const name = tuple[1]

// It can also be accessed using array deconstruction
const [age, name] = tuple
Copy the code

Usage scenarios of tuples

  1. Returns multiple return values in a function
  2. React useState() HookThe tuple type is returned
  3. Object.entries()Gets an array of all key values in an object, each of which is a tuple

Enumerated type

In the development process, it is often necessary to use a number of values to represent a number of states. This data structure is very common in other languages, but it is not available in JS. It is usually simulated by objects.

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

const page = {
	title: 'typeScript guide'.content: 'content'.status: PostStatus.Draft
}
Copy the code

The characteristics of

We now have enum types in TypeScript, which are:

  1. Give a set of values a semantically better name
  2. There are only a few fixed values in a set of data, and there is no possibility of going out of range

DEMO

Here’s an example: Here are the three states of a published book:

  • DraftIs the draft state:0
  • UnpublishedIs unpublished:1
  • PublishedIs published:2
// enum is the enumeration type followed by the enumeration name. It uses an equal sign instead of a colon
enum PostStatus {
  Draft = 0,
  Unpublished = 1,
  Published = 2
}
// Use objects. To use
const post = {
  title: 'typeScript guide'.content: 'content'.status: PostStatus.Published / / 1 / / 0
}
Copy the code

If = is not added, the value is accumulated from 0 by default

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

If the first value is given, all subsequent members will be added to it

enum PostStatus2 {
  Draft = 6./ / 6
  Unpublished, / / 7
  Published / / 8
}
Copy the code

Enumerations can also be strings. Strings cannot grow by themselves, so each one needs to be assigned

enum PostStatusStr {
  Draft = 'string1',
  Unpublished = 'string2',
  Published = 'string3'
}
Copy the code

Enumeration types invade code

Enumerations invade runtime code and, in short, affect compilation results. Most TypeScript types are eventually compiled and removed just for type-checking at development time, whereas enumerations are compiled into bi-directional key-value objects that can find keys by value and values by key.

The following code remains in the project

var PostStatus;
(function (PostStatus) {
	The inner layer uses the enumeration's key to store the enumeration's value, and the outer layer uses the enumeration's value to store the enumeration's key
    PostStatus[PostStatus["Draft"] = 0] = "Draft";
    PostStatus[PostStatus["Unpublished"] = 1] = "Unpublished";
    PostStatus[PostStatus["Published"] = 2] = "Published";
})(PostStatus || (PostStatus = {}));
Copy the code

The purpose of this is to dynamically obtain the enumeration name based on the enumeration value

PostStatus[0] // Draft
Copy the code

If we do not use the above statement to access the key, we recommend using constant enumeration

Constant enumeration

Constant enumerations simply add const in front of the enum so that the code is not intrusive. The code for the above bidirectional key-value pairs is removed, just with some comments added at the end.

  • Do not addconstCompiled code for
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
};
Copy the code
  • addconstCompiled code for
// The PostStatus value above will be removed and replaced with the value directly below
var post = {
    title: 'Hello TypeScript'.content: 'content'.status: 2 /* Published */ / / 1 / / 0
};
Copy the code

TypeScript learns maps