Typescript 入门

84 阅读1分钟

大神链接

  • 字符串
let str:string = 'Hello World!';
  • 数值类型
let num:number = 18;
  • bool类型
let boolValue:boolean = true;
  • undefined
let undefinedValue:undefined = undefined;
  • null
let nullValue:null = null;
  • 对象
let obj:object = {x:1};
  • 数组
let arr:string[] = ["1","2","3"];
let array:Array<string> = ["Roy","Ei"];
  • 联合类型数组
let arr:(number|string)[] = [];
arr = [1,"2",3,"4"];
  • 对象数组
interface ArrayObj {
    name:string,
    age:number
}
let array:ArrayObj[] = [{name:'Roy',age:18}];
  • 函数
function sum(x:number,y:number):number {
    return x + y;
}
  • 接口定义函数
interface InterfaceFunc {
    sum(x:number,y:number):boolean;
}
  • 可选参数
function buildName(firstName:string,lastName?:string) {
    if (lastName) {
        return firstName + " " + lastName;
    } else {
        return firstName;
    }
}
let CaptainRoy = buildName("Captain","Roy");
let Roy = buildName("Roy");
  • 默认参数
function buildName(firstName:string,lastName:string='Roy') {
    return firstName + " " + lastName;
}
let CapatinRoy = buildName("Captain","Cat");
let Roy = buildName("Captain");