其他分享
首页 > 其他分享> > typescript

typescript

作者:互联网

基础类型

Boolean

number

string

null

undefined

any

void

never

object type

let obj33:{name:string,age:number}={
    name:'11',
    age:11    
}

*array[] 数组类型

const list: number[] = [12, 23, 34]
//泛型
const listA: Array<number> = [1, 2, 3]
class Person {}
const LinYY: Person  = new Person()
const getNumber: () => number = () => {
    // return 'LinYY'   报错
    return 123
}

// 要求返回值是string 字符类型
const getString: () => string = () => {
    return 'LinYY'
    // return 123
}

interface 自定义类型

//interface
interface Point {
    x: number,
    y: string
}
const point: Point ={
    x:123,
    y:'123'
}

type alias 类型别名 不是ts的基本数据类型,常用于提取公共类型

type User = { name: string, age: number }
let male: User = {name: 'LinYY', age: 18}
let famale: User = {name: 'nana', age: 18}

数组和元组

数组的类型注解

//对象数组
const objarr:{name:string,age:number}[]=[{
    name:'123',
    age:12    
}

typescript断言

类型断言

let someValue:any = 'this is a string';
let str22:number=(<string>someValue).length;

// as 语法
let str33:number=(someValue as string).length;

非空断言

忽略undefined和null类型

function my(mystr: string | undefined | null) {
    // const str:string=mystr;
    const str2:string=mystr!;
}

调用函数时忽略undefined

type Num=()=>number;
function fn(num:Num|null){
    const num1=num();//error
    const num2=num!();
}

确定赋值断言

类型守卫

联合类型

TS中的this TS是JS的超集 this指向相同

标签:typescript,const,string,number,类型,null,name
来源: https://www.cnblogs.com/Goodnighter/p/16673522.html