The eight types of javaScript in typeScript

The eight types of javaScript in typeScript

1. Boolean type

let bool: boolean = false
bool = true
// bool = 'hello' // 不能将类型“"hello"”分配给类型“boolean”。
// bool = 123 // 不能将类型“123”分配给类型“boolean”。

// 赋给 bool 的值也可以是一个计算之后结果是布尔值的表达式,比如:

let b = !!0
console.log(b) // false

2. Numerical type

let num: number = 0
num = 123
num = 0b1111011 // 二进制的 123
num = 0o173 // 八进制的 123
num = 0x7b // 十六进制的 123

// num = '100' // 不能将类型“"100"”分配给类型“number”。
// num = false // 不能将类型“false”分配给类型“number”。

3. String

In the string type, you can use single and double quotes to wrap the content, but maybe the tslint rule you use will detect the quotes. Whether to use single or double quotes can be configured in the tslint rule. You can also use ES6 syntax-template strings, it is more convenient to concatenate variables and strings.

let str: string = 'hello'
let st: string = `${str}`

// str = 100 // 不能将类型“100”分配给类型“string”。
// str = false // 不能将类型“false”分配给类型“string”。

let s: 'STRING'
// 另外还有个和字符串相关的类型:
// 即把一个字符串字面量作为一种类型,比如上面的字符串"STRING",当你把一个变量指定为这个字符串类型的时候,就不能再赋值为其他字符串值了,如:
// s = 'a' // 不能将类型“"a"”分配给类型“"STRING"”。

4. Array

// 在 TypeScript 中有两种定义数组的方式:
let list1: number[] = [1, 2, 3]
let list2: Array<number> = [1, 2, 3]

// let list3: ReadonlyArray<number> = [1, 2, 3] // 即只读数组。

list3 = []

// console.log(list3)

The first form uses number[]the form to specify that the elements of this type are all number type array types.
This writing is the recommended writing,
and the second writing can also be used.
Note that the two types of writing numberspecify the type of array elements, and you can also specify any type of array elements here.
If you want to specify an array of elements can be either numeric or a string, then you can use this way: number|string[],
when we learn this way of union types will be mentioned later.

When you use the second form of definition, tslint may warn you to use the first form of definition. If you just want to use the second form, you can "array-type": [false]turn off tslint's detection of this by adding in the rules of tslint.json .

5.null

let u: undefined = undefined
// 这里可能会报一个 tslint 的错误:Unnecessary initialization to 'undefined',就是不能给一个值赋 undefined,但我们知道这是可以的,所以如果你的代码规范想让这种代码合理化,可以配置 tslint,将"no-unnecessary-initializer"设为 false 即可

6.undefined

let n: null = null

7.object

let obj: object

obj = { name: 'object' }

// console.log(obj.name) // 类型“object”上不存在属性“name”

8.symbol

let sym: symbol = Symbol('你好')

console.log(sym)

Guess you like

Origin blog.csdn.net/qq_39953537/article/details/102685392