记一次typescript入门基础笔记ts

一、基础类型:
boolean为布尔值类型,如let flag:boolean = true;
number为数值类型,如let age:number = 19;
string为字符串类型,如let name:string='zhangsan';
数组类型,如let list: data:number[]=[1,2,3];
多维数组:如let dataArr:number[][]=[[1,2,3],[4,5,6]];
元组类型,如let x: [ string, number ] = [ "hello", 10 ]
枚举类型,如enum Sex {
MALE,
FAMALE,
UNKNOW
}
let sex:Sex=Sex.FAMALE;
any为任意类型,如let unknow: any = 10; unknow= "不确定的类型";
void为空类型,如let sky: void = undefined
null和undefined
never表示没有值的类型,如function fn(msg: string): never { throw new Error(msg); }
联合类型可以用 | 隔开,如let da:number | string=12;表示可以是number或string类型

二、例子:

// boolean
const flag:boolean=true;
console.log(flag);

// 数值
const age:number=19;
console.log(age);

// 字符串
let name:string='zhangsan';
name='100';
console.log('name:', name);
let lang:any='ts';
lang=50;
console.log(lang);

// 对象
const obj:object={};
console.log(obj);

// 数组
const data:number[]=[1,2,3];
data[0]=10;
data[3]=40;
const data2:string[]=['one','two','three'];

// 多维数组
const dataArr:number[][]=[[1,2,3],[4,5,6]];

// 枚举
enum Sex {
    MALE,
    FAMALE,
    UNKNOW
}
let sex:Sex=Sex.FAMALE;
console.log(sex);
console.log(Sex[sex]);
switch (+sex) {
    case Sex.MALE:
        console.log('男');
        break;
    case Sex.FAMALE:
        console.log('女');
        break;
    case Sex.UNKNOW:
        console.log('未知');
        break;
    default:
        break;
}

// 联合类型
let da:number | string=12;
da='qqq';
console.log(da);

let da2:number | number[]=4;
da2=[1,5,6];
console.log(da2);

你可能感兴趣的:(记一次typescript入门基础笔记ts)