Types in TypeScript include: Primitive types (Boolean, number, String, void, null, undefined, bigINT, symbol), any, unknown, never, tuple, enumeration enum, Array Array, object
String String type
// Single or double quotes
let myName: string = 'Tom';
let myAge: number = 25;
// Template string
let sentence: string = `Hello, my name is ${myName}.
I'll be ${myAge + 1} years old next month.`;
${expr} is used to embed expressions in template strings.
Copy the code
Boolean Indicates the Boolean type
The most basic data types are simple true/false values. Booleans cannot be assigned to other values
const registered: boolean = false // Variable name: variable type
const done: boolean = Boolean(0)
Copy the code
Number Number type
Binary, decimal, and hexadecimal numbers can all be represented by the number type.
let decLiteral: number = 6
let goldenSection: number = 0.618
let hexLiteral: number = 0xf00d
let binaryLiteral: number = 0b1010
let octalLiteral: number = 0o744
let notANumber: number = NaN
Copy the code
bigint
The largest integer that can be represented by Number in JavaScript is 2^ 53-1, which can be written as number.max_safe_INTEGER. If the boundary is exceeded, it can be represented by BigInt, which can represent arbitrarily large integers.
grammar
const theBiggestInt: bigint = 9007199254740991n // add n to integer literals
const alsoHuge: bigint = BigInt(9007199254740991) // Call function BigInt()
const hugeString: bigint = BigInt("9007199254740991")
theBiggestInt === alsoHuge // true
theBiggestInt === hugeString // true
Copy the code
BigInt differs from Number:
- BigInt cannot be used for methods in Math objects.
- BigInt cannot be mixed with any Number instances; both must be converted to the same type.
- The BigInt variable may lose precision when converted to the Number variable.
//number
const biggest: number = Number.MAX_SAFE_INTEGER
const biggest1: number = biggest + 1
const biggest2: number = biggest + 2
biggest1 === biggest2 // true overflows no matter how much you add to the precision, so the two values are equal.
//bigint
const biggest: bigint = BigInt(Number.MAX_SAFE_INTEGER)
const biggest1: bigint = biggest + 1n
const biggest2: bigint = biggest + 2n
biggest1 === biggest2 // false The container is not full
Copy the code
Conversion between Number and BigInt will result in loss of accuracy.
- Do not convert between two types.
- Use BigInt only if the value can be greater than 2^ 53-1.
The type information
typeof 10n= = ='bigint' // true
typeof BigInt(10) = = ='bigint' // true
typeof 10= = ='number' // true
typeof Number(10) = = ='number' // true
Copy the code
operation
BigInt can normally be evaluated with +, -, *, /, **, and % symbols
const previousMaxSafe: bigint = BigInt(Number.MAX_SAFE_INTEGER) // 9007199254740991n
const maxPlusOne: bigint = previousMaxSafe + 1n // 9007199254740992n
const multi: bigint = previousMaxSafe * 2n // 18014398509481982n
constSubtr: bigint = multi -10n // 18014398509481972n
const mod: bigint = multi % 10n // 2n
const bigN: bigint = 2n支那54n // 18014398509481984n
const divided: bigint = 5n / 2n // 2n, not 2.5n When the/operator is used, the decimal part is not returned
Copy the code
Comparison and condition
// Compare Number with BigInt
0n= = =0 // false
0n= =0 // true
1n < 2 // true
2n > 1 // true
2 > 2 // false
2n > 2 // false
2n> =2 // true
////Number and BigInt
if (0n) {
console.log('Condition holds! ');
} else {
console.log('Condition does not hold! '); // Output the result
}
0n || 10n // 10n
0n && 10n // 0n
Boolean(0n) // false
Boolean(10n) // true
!10n // false
!0n // true
Copy the code
Any type
You cannot determine the type of the variable and do not want the type checker to check the values. You can use any. A variable declared as any can be assigned a value of any type
let input: any = 'nothing'
input = 0 // ok
input = true // ok
input = [] // ok
input = null // ok
input = Symbol('any') // ok
Copy the code
If a data is of type any, then any of its attributes can be accessed, even if the attribute does not exist:
let anything: any = 10
anything.eat() // ok
anything.name // ok
anything[0] // ok
new anything() // ok
anything() // ok
Copy the code
The any type can do almost anything, making it easy to write correctly typed code that performs exceptions. We use TypeScript for robustness, so minimize the use of any.
Void type
When a function returns no value, its return value type can be defined as void:
function doNothing() :void {
let a = 10
}
Copy the code
Declaring a void variable doesn’t help much, because you can only assign it to undefined and null:
let nothing: void = undefined
Copy the code
Null and undefined
Undefined and NULL are subtypes of all types.
StrictNullChecks are enabled by default. If you set strictNullChecks to false in tsconfig.json, strictNullChecks will not return an error, but try not to:
let num: number = undefined
let list: number[] = undefined
let name: string = undefined
Copy the code
Never type
The never type represents values that never exist. For example, the never type is the return type of function expressions or arrow function expressions that always throw an exception or have no return value at all. Variables can also be of type never, when they are bound by type protection that is never true.
The never type is a subtype of any type, including null and undefined, and can be assigned to any type; Variables declared as type never can only be assigned by type never. Even any cannot be assigned to never.
let x: never;
let y: number;
// Error running. The numeric type cannot be converted to never
x = 123;
// The never type can be assigned to the never type
x = (() = >{ throw new Error('exception')}) ();// It works correctly. The never type can be assigned to a numeric type
y = (() = >{ throw new Error('exception')}) ();// A function that returns never must have an unreachable end
function error(message: string) :never {
throw new Error(message);
}
// The inferred return value type is never
function fail() {
return error("Something failed");
}
// A function that returns never must have an unreachable end
function infiniteLoop() :never {
while (true) {}}Copy the code
Unknown type
An unknown type can only be assigned to any type and the unknown type itself
Use unknown instead of any where you would get an arbitrary value, but do not know the exact type.
let value: unknown
let value1: unknown = value // OK
let value2: any = value // OK
let value3: boolean = value // Error
let value4: number = value // Error
let value5: string = value // Error
let value6: object = value // Error
let value7: any[] = value // Error
Copy the code
An unknown type cannot be executed or instantiated before it is determined as a type. This protects the type to some extent:
let value: unknown
value.foo.bar // Error
value.trim() // Error
value() // Error
new value() // Error
value[0] [1] // Error
Copy the code
Array Array type
// The element type is followed by []:
let list: number[] = [1.2.3]
let names: string[] = ['Sherlock'.'Watson'.'Mrs. Hudson']
// Array generic, Array< element type > :
let list: Array<number> = [1.2.3]
let names: Array<string> = ['Sherlock'.'Watson'.'Mrs. Hudson']
let list: any[] = ['Sherlock'.1887] // Mix various element types
Copy the code
Symbol
The value of the symbol type is created through the Symbol constructor. Each Symbol value returned from Symbol() is unique.
let sym2 = Symbol("key");
let sym3 = Symbol("key");
sym2 === sym3; // False, symbols are unique
Copy the code
The object type
Object represents a non-primitive type, that is, a type other than number, string, Boolean, symbol, NULL, or undefined.
let obj: object
// Enumeration type
enum TokenType {
ACCESS = 'accessToken',
REFRESH = 'refreshToken'
}
obj = TokenType
obj = [1.2.3]
obj = [1.'string'] // Tuple type
obj = { a: 1 }
Copy the code
You can see that enumerations, arrays, tuples, and ordinary objects are all of type Object.
With Falsy Truthy
Truthy is a value whose converted value is’ true ‘, Falsy is a value that is assumed to be converted to ‘false’ in a Boolean context
Variable types | Truthy | Falsy |
---|---|---|
boolean | true | false |
string | Non-empty string | ‘ ‘ |
number | Other figures | 0 / NaN |
null | — | Always is false |
undefined | — | Always is false |
object | Always true, including {}, [], () => {} | — |
Empty functions, empty arrays, and empty objects are all Truthy and return true
The operator! Represents the inverse, and gets a Boolean value:
let fn = () = > {}
let obj = {}
let arr: never[] = []
console.log(! fn)// false
console.log(! obj)// false
console.log(! arr)// false
let num = 10
let str = 'imooc'
console.log(! num)// false
console.log(! str)// false
let n = null
let u = undefined
let N = NaN
let z = 0
console.log(! n)// true
console.log(! u)// true
console.log(! N)// true
console.log(! z)// true
Copy the code
Operator!!!!! Represents the value of a variable after being cast to a Boolean value:
let fn = () = > {}
let obj = {}
let arr: never[] = []
console.log(!! fn)// true
console.log(!! obj)// true
console.log(!! arr)// true
let num = 10
let str = 'imooc'
console.log(!! num)// true
console.log(!! str)// true
let n = null
let u = undefined
let N = NaN
let z = 0
console.log(!! n)// false
console.log(!! u)// false
console.log(!! N)// false
console.log(!! z)// false
Copy the code
Pay attention to
- TypeScript describes types in lowercase. Such as Boolean, number, string, etc.
- Don’t abuse any;
- Uppercase names such as Boolean, Number, and String represent JavaScript constructors:
let a: Number = new Number('10') // a === 10 is false
// New Number('10') is a constructor, which is essentially an object
let b: number = Number('10') // b === 10 is true
// Number('10') and 10 are both methods of declaring the Number 10, which is essentially a Number
a instanceof Number // true
b instanceof Number // false
Copy the code