我爱编程

typescript入门

2018-08-03  本文已影响0人  我竟无言以对_1202

安装typescript

npm install -g typescript

在vscode中自动编译typescript

tsc --init

{
  "compilerOptions": {
   "target": "es5",
   "noImplicitAny": false,
   "module": "amd",
   "removeComments": false,
   "sourceMap": false,
   "outDir": "src/js"//你要生成js的目录
  }
}

typescript基本数据类型

var isBool:boolean = false;

function tell(){
    alert(isBool);
}

tell();
var num:number = 10;
console.log(num);
var str:string = "帅哥";
function tell(){
    str+="hello ";
    alert(str);
}

tell();
// 第一种方式
var list1:number[] = [1,2,3];

function tell(){
    alert(list1[0]);
    alert(list1[1]);
    alert(list1[2]);
}
tell();
// 第二中方式
var list2:Array<string> = ['帅哥','美女'];

function tell2(){
    alert(list2[0]);
    alert(list2[1]);
}
tell2();
enum Color{Red,Green,Blue};

var colorName:string = Color[1];
alert(colorName); // Green

// 修改下标
enum Color{Red=1,Green,Blue};

var colorName:string = Color[1];
alert(colorName); // Red
var notsure:any =10;
var list:any[] = [1,"hello",false];
function warnUser(): void {
    alert("This is my warning message");
}

声明一个void类型的变量没有什么大用,因为你只能为它赋予undefined和null:

let unusable: void = undefined;

函数

let myAdd = function(x: number, y: number): number { return x + y; };
// 完整函数类型
let myAdd: (x: number, y: number) => number =
    function(x: number, y: number): number { return x + y; };

function buildName(firstName: string, lastName: string) {
    return firstName + " " + lastName;
}

let result1 = buildName("Bob");                  // error, too few parameters
let result2 = buildName("Bob", "Adams", "Sr.");  // error, too many parameters
let result3 = buildName("Bob", "Adams");  

JavaScript里,每个参数都是可选的,可传可不传。 没传参的时候,它的值就是undefined。 在TypeScript里我们可以在参数名旁使用 ?实现可选参数的功能。 比如,我们想让last name是可选的:

function buildName(firstName: string, lastName?: string) {
    if (lastName)
        return firstName + " " + lastName;
    else
        return firstName;
}

let result1 = buildName("Bob");  // works correctly now
let result2 = buildName("Bob", "Adams", "Sr.");  // error, too many parameters
let result3 = buildName("Bob", "Adams");  // ah, just right
function buildName(firstName: string, lastName = "Smith") {
    return firstName + " " + lastName;
}

let result1 = buildName("Bob");                  // works correctly now, returns "Bob Smith"
let result2 = buildName("Bob", undefined);       // still works, also returns "Bob Smith"
let result3 = buildName("Bob", "Adams", "Sr.");  // error, too many parameters
let result4 = buildName("Bob", "Adams");         // ah, just right
function buildName(firstName: string, ...restOfName: string[]) {
  return firstName + " " + restOfName.join(" ");
}

let employeeName = buildName("Joseph", "Samuel", "Lucas", "MacKinzie");
function attr(name:string):string;
function attr(age:number):number;

function attr(nameorage:any):any{
    if(nameorage&&typeof nameorage === "string"){
        alert("姓名");
    }else{
        alert("年龄");
    }
}

attr("hello");
attr(18);

typescript类

class Person{
    name:string;
    age:number;
    constructor(name:string,age:number){
        this.name = name;
        this.age = age;
    }
    print(){
        return this.name+":"+this.age;
    }
}

var p = new Person("aa",18);
alert(p.print());

class Person{
    name:string;
    age:number;
    constructor(name:string,age:number){
        this.name = name;
        this.age = age;
    }
    tell(){
        return this.name+":"+this.age;
    }
}

class Student extends Person{
    school:string;
    constructor(school:string){
        super("li",80);
        this.school = school;
    }
    tell(){
        return this.name+":"+this.age+":"+this.school;
    }
}

var s = new Student("school");

alert(s.tell());

接口

interface LabelledValue {
  label: string;
}

function printLabel(labelledObj: LabelledValue) {
  console.log(labelledObj.label);
}

let myObj = {size: 10, label: "Size 10 Object"};
printLabel(myObj);
interface SearchFunc{
    (source:string,subString:string):boolean;
}

var mySearch:SearchFunc;
mySearch = function(source:string,subString:string){
    var result = source.search(subString);
    if(result!=-1){
        return true;
    }else{
        return false;
    }
}
interface StringArray{
    [index:number]:string;
}

var myArray:StringArray;

myArray=["li","wang"];
alert(myArray[1]);
interface ClockInterface{
    currentTime:Date;
    setTime(d:Date);
}

class Clock implements ClockInterface{
    currentTime:Date;
    setTime(d:Date){
        this.currentTime = d;
    }
    constructor(h:number,m:number){

    }
}
interface Shape{
    color:string;
}

interface PenStroke{
    penWidth:number;
}

interface Square extends Shape,PenStroke{
    sideLength:number;
}

var s = <Square>{};
s.color = "blue";
s.penWidth = 10;
s.sideLength = 10;

混合类型

interface Counter{
    interval:number;
    reset():void;
    (start:number):string;
}

var c:Counter;
c(10);
c.reset();

泛型

function Hello<T>(arg:T):T{
    return arg;
}
var output = Hello<string>("hello");
alert(output);
function Hello<T>(arg:T):T{
    alert(arg.length);
    return arg;
}

上面的代码因为没有指定泛型,所以没有length属性会报错

function Hello<T>(arg:T[]):T[]{
    alert(arg.length);
    return arg;
}

上面代码指定泛型-数组,所以有length

function Hello<T>(arg:T[]):T[]{
    return arg;
}

var list:Array<string> = Hello<string>(["1","2","3"]);
for(var i=0;i<list.length;i++){
    alert(list[i]);
}
function Hello<T>(arg:T):T{
    return arg;
}

var myHello:<k>(arg:k)=>k = Hello;

alert(myHello("hello"));
function Hello<T>(arg:T):T{
    return arg;
}

var myHello:{<T>(arg:T):T} = Hello;
alert(myHello("Hello"));
class HelloNumber<T>{
    Ten:T;
    add:(x:T,y:T)=>T;
}

var myHelloNumber = new HelloNumber<number>();
myHelloNumber.Ten = 10;
myHelloNumber.add = function(x,y){
    return x+y;
}
alert(myHelloNumber.Ten);
alert(myHelloNumber.add(10,10));
上一篇下一篇

猜你喜欢

热点阅读