illustrate
TypeScript supports almost the same data types as JavaScript, and also provides additional data types
Boolean value
const flag: boolean = true;
number
onst count: number = 10;
string
Single quotes, double quotes, and template strings can all represent strings
const name: string = 'Jack';
const address = "北京朝阳";
const info: string = `我是${name},来自${address}`;
array
Operate arrays in the same way as JavaScript, defined in the following two ways
const arr1: string[] = ['苹果', '橘子'];
const arr2:Array<number> = [1, 2, 3];
tuple
Define an array of known elements and types, the element types and the order of definition should be consistent
const arr1: [number, string] = [1, '水果'];
const arr2: [string, number] = [1, '水果']; // 提示类型不匹配
enumerate
The enum type is an additional supplement to the JavaS data type. By default, it is sorted from 0
enum Colors {
Red, Green, Blue
}
console.log(Colors.Red) // 0
console.log(Colors[1]) // Gree
You can also manually specify the number of a member or specify the number of all members
enum Colors {
Red=1, Green, Blue
}
console.log(Colors.Red) // 1
console.log(Colors[3]) // Gree
Any type
Indicates that the data can be of any data type. When the current data type is unclear, use any definition to skip compile-time type checking
let anyData: any = 4;
let anyArray: Array<any> = ['1', 1, {name: 'Jack'}]
Void
Indicates that there is no data type, and is often used in function return values
function testVoid():void{
console.log('testVoid')
}
Null and Undefined
The type is not very useful, and the meaning is consistent with null and undefined in JavaScript
Never
The never type represents a value type that never exists. The never type is a subtype of any type and is assignable to any type; however, no type is a subtype of or assignable to the never type (except never itself). Even any cannot be assigned to never.
Objec
object is a non-primitive data type and is a type other than number, string, boolean, symbol, null or undefined
type assertion
When a variable may have multiple data types or define any type, it is used when we need to do different business processing according to different types.
Official note:
Sometimes you'll run into a situation where you know more about the details of a value than TypeScript does. Usually this happens when you clearly know that an entity has a more specific type than it already has.
This is the way to tell the compiler, "trust me, I know what I'm doing" through type assertions. Type assertions are like type conversions in other languages, but without special data checking and destructuring. It has no runtime impact, it only works during the compile phase. TypeScript assumes that you, the programmer, have performed the necessary checks.
Two ways of type assertion: "angle brackets" syntax and as syntax
const anyData = '类型断言'
const len1: number = (<string>anyData).length
const len2: number = (anyData as string).length