JavascriptTypeScript阅读笔记

0

TypeScript阅读笔记

阅读:538 时间:2022年01月24日

数据类型number 数字const num: number = 1string 字符串const str: string = 'lenton'boole...

数据类型

number 数字

const num: number = 1


string 字符串

const str: string = 'lenton'


boolean 布尔值

const bl: boolean = true


array 数组

const arr1: Array<number> = []
const arr2: number[] = []


Tuple 元组类型用来表示已知元素数量和类型的数组,各元素的类型不必相同,对应位置的类型需要相同

const x: [string, number] = ['lenton', 30]


enum 枚举

enum Color {Red, Green, Blue}
let color: Color = Color.Red
console.log(Color.Blue) // 2

手动赋值

enum Color { Red = 5, Blue = 3, Yellow = 1 }
console.log(Color.Blue) // 3


void 空值  用于标识方法返回值的类型,表示该方法没有返回值

function say(): void {
    console.log('Hello !')
}


null 表示对象值缺失


undefined 用于初始化变量为一个未定义的值


never never 是其它类型(包括 null 和 undefined)的子类型,代表从不会出现的值


any 变量的值会动态改变时,比如来自用户的输入,任意值类型可以让这些变量跳过编译阶段的类型检查

let x: any = 1


如果一个类型可能出现多种类型, 可以用 | 来支持多种类型

let a: number | string | string[]
a = 'lenton'
a = 23
a = ['lenton', 'hello']



变量声明

var [变量名] : [类型] = 值;


类型断言(Type Assertion)

类型断言可以用来手动指定一个值的类型,即允许变量从一种类型更改为另一种类型

const str: string = '1'
const num: number = <any> str


any 断言,例如在window对象上添加属性

(window as any).foo = 1;



函数

可选参数和默认参数

可选参数使用问号标识 ?

function fullName(firstName:string = 'lenton', lastName?: string): string {
    return firstName + ' ' + lastName
}


函数重载

参数类型不同:

function disp(arg: string): void
function disp(arg: number, arg2: string): void

function disp(arg: string | number, arg2?: string): void {
    if (typeof arg === 'string') {
        console.log(arg)
    } else {
        console.log('reload', arg, arg2)
    }
}

disp(1, 'lenton')
// reload 1 lenton




接口

interface Person {
    name: string,
    age: number,
    say: (word: string) => string
}

const girl: Person = {
    name: 'alina',
    age: 23,
    say: (arg) => {
        console.log(arg)
        return arg
    }
}

girl.say('Hello world')




声明

declare const jQuery: (selector: string) => any;




类型别名

type Name = string;
type NameResolver = () => string;
type NameOrResolver = Name | NameResolver;
function getName(n: NameOrResolver): Name {
    if (typeof n === 'string') {
        return n;
    } else {
        return n();
    }
}







发表评论说说你的看法吧

精品模板蓝瞳原创精品网站模板

^