Typescript入门 | 青训营笔记

71 阅读1分钟

基础数据类型

/字符串/const q = 'string';const q : 'string';
/布尔值/const w = true;const w : true;
/数字/const e = 1;const e : 1;
/null/const r = null;const r : null;
/undefined/const t=nudefined;const t : nudefined;

对象类型

const bytedacer: IBytedabcer = {  
    jobId:163764,  
    name:'Li',  
    sex:'man',  
    age:12,  
    hobby:'reading',  
}
interface IBytedancer{  
    /*只读属性:约束属性不可在对象初始化外赋值*/
    readonly jobId: number;
    name: string;
    sex: 'man' | 'woman' | 'other' |;
    age: number;
     /*可选属性:定义该属性可以不存在*/
    hobby?:string;
     /*任意属性:约束所有对象属性都必须是该属性的子类型*/
    [key: string]: any;
}
    /*报错:无法分配到“jobId”,因为它只是只读属性*/
    bytedancer.jobId = 12344;
    /*报错:缺少属性“name”,hobby可缺省*/
     const bytedancer2: bytedancer = {
           jobId: 2563,
           sex: 'woman',
           age: 13,
   }   

数组类型

/*类型+方括号  表示*/
type IArr1 = number[];
/*泛型表示*/
type IArr2 = Array<string | number | Recode<string, number>>;
/*元组表示*/
type IArr3 = [number, number, string, string];
/*接口表示*/
interface IArr4 = {
    [key: number]: any;
}

补充类型

/*空类型,表示无赋值*/
type IEmptyFunction = () => void;
/*任意类型,所有类型的子类型*/
type IAnyType = any;
/*泛型*/
type INumArr = Array<number>;

泛型

/*泛型类*/
class IMan<T> {
    instance: T;
}