typescript——基础类型与变量

基础类型

boolean

let bool:boolean = true;
console.log('bool: ', bool, "type: ", typeof bool);

number

let num:number = 10;
console.log('num: ', num, "type: ", typeof num);

string

let str:string = "str123";
console.log('str: ', str, "type: ", typeof str);

Array<>

let arr:Array<number> = [1,2,3];
console.log("arr: ", arr, "type: ", typeof arr);

enum

enum Color {red, bule, yellow}
let colvalue: Color = Color.bule;
console.log("enum: ", colvalue, "type: ", typeof colvalue);

tuple

let x:[string, number] = ["ABC", 123];
console.log("tuple : ", x,"type: ", typeof x);

let y:[string, number, string] = ["ABC", 123, "DEF"];
console.log("three tuple : ", y,"type: ", typeof y);

any

let arrany:any = ["ABC", 123];
console.log("arrany: ", arrany, "type: ", typeof arrany);

void

function fun():void{

}

null和 undefined

  • 默认情况下null和undefined是所有类型的子类型。
  • strictNullChecks: null和undefined只能赋值给void和它们各自。

never类型表示的是那些永不存在的值的类型。

  • never类型是任何类型的子类型,也可以赋值给任何类型;
  • 没有类型是never的子类型或可以赋值给never类型(除了never本身之外)。 即使 any也不可以赋值给never。

object

let obj:object = {"ABC":123};
console.log("obj: ", obj["ABC"], "type: ", typeof obj);

类型断言 即 类型转化

  • 类型断言有两种形式。 其一是“尖括号”语法:
let someValue: any = "this is a string";

let strLength: number = (<string>someValue).length;
  • 另一个为as语法:
let strLength1: number = (someValue as string).length;

变量声明

var 作用域: 函数作用域或全局作用域

  • 多次声明同一个变量并不会报错

let : 块作用域

  • 暂时性死区: 不能在被声明之前读或写。 虽然这些变量始终“存在”于它们的作用域里,但在直到声明它的代码之前的区域都属于暂时性死区。

  • 块级作用域变量需要在明显不同的块里声明

    • 不能在1个作用域里多次声明
  • 屏蔽: 在一个嵌套作用域里引入一个新名字的行为称做屏蔽。

    function f(condition, x) {
        if (condition) {
            let x = 100;
            return x;
        }
    
        return x;
    }
    

const: 块作用域

  • 不能对它们重新赋值, 引用的值是不可变的

链接

基础类型文档
变量声明文档

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值