basic type
array
- The first: element type []
let arr: number[] = [1,2,3]
- The second type: Array generics -Array<element type>
let arr: Array<number> = [1,2,3]
Tuple
Represents an array of known number and type of elements
let arr: [string, number]
a = ['RenNing', 18]
When accessing out-of-bounds elements, the union type will be used instead
arr[1] //18
arr[3] = 'world' // (string | number) 类型
Enumeration enum
An addition to JavaScript
the standard data types.
enum Color {
Red, Green, Blue}
let c: Color = Color.Green //1
By default, elements are numbered starting from 0 ; member values can be manually specified
enum Color{
Red = 3, Green, Blue = 8}
let c: Color = Color.Green //4
Channel his name through the value of the enum
let colorName: string = Color[3] //red
Any
Void
void
Type is like any
the opposite of type, it means there is no type at all.
When a function does not return a value, you usually see that its return type isvoid
Declaring a void
variable of a type is not very useful because you can only assign undefined
andnull
Null and Undefined
let u: undefined = undefined;
let n: null = null;
By default null
and undefined
are subtypes of all types.
null
and can be undefined
assigned to number
variables of type.
let a:number = null
When you specify --strictNullChecks
flags, null
and undefined
can only be assigned to void
and their respective
somewhere you want to pass in an string
or null
or undefined
, you can use the union typestring | null | undefined
Never type
Identifies the type of a value that never exists
For example, never
the type is the return type of a function expression or an arrow function expression that always throws an exception or never returns a value at all;
never
A type is a subtype of, and is assignable to, any type; however, no type is never
a subtype of, or is assignable to, never
a type
function error(message: string) :never {
throw new Error(message)
}
type assertion
Form 1: "angle brackets" syntax
let someValue: any = 'this.is a string'
let strLength: number = (<string>someValue).length
Form 2: as syntax
let strLength: number = (someValue as string).length;