TypeScript - 01 初探

2019-12-11  本文已影响0人  Lisa_Guo

Typescript 是Javascript的一个子集,提供在编译期间的类型检查等额外功能,最终编译后的还是Javascript

// 安装ts
npm install typescript -g

// 编译ts文件,输出js
tsc main.ts

类型注释( type annotation)

为变量增加类型说明,格式为 variable:type
如下函数只接受string类型的参数,调用时传参不匹配则编译时报错

function greeter(person: string) {
    return "Hello, " + person;
}

let user = [0, 1, 2];

document.body.textContent = greeter(user);

编译报错:error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'string'.

编译期间可检测出对变量赋值时类型匹配度

接口(interface)

interface是一个规范约定,定义了一个对象包含的属性。也就是定义了一个复杂数据类型

interface Person {
   firstName: string;
   lastName: string;
}

function greeter(person: Person) {
    return "Hello, " + person.firstName + " " + person.lastName;
}

let user = { firstName: "Jane", lastName: "User" };

document.body.textContent = greeter(user);

编译后的js为

function greeter(person) {
    return "Hello, " + person.firstName + " " + person.lastName;
}
var user = { firstName: "Jane", lastName: "User" };
document.body.textContent = greeter(user);

class

// public修饰符会自动创建同名属性变量
class Student {
  fullName: string;
  constructor(public firstName: string, public lastName: string) {
     this.fullName = firstName + ' ' + lastName
 }
 sayHello() {
   console.log(this.fullName + ' is saying hello')
 }
}

interface Person {
   firstName: string;
   lastName: string;
}

function greeter(person: Person) {
   return "Hello, " + person.firstName + " " + person.lastName;
}

let user = new Student("Jane", "M.");

document.body.textContent = greeter(user);

编译后文件为

var Student = /** @class */ (function () {
    function Student(firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.fullName = firstName + ' ' + lastName;
    }
    Student.prototype.sayHello = function () {
        console.log(this.fullName + ' is saying hello');
    };
    return Student;
}());
function greeter(person) {
    return "Hello, " + person.firstName + " " + person.lastName;
}
var user = new Student("Jane", "M.");
document.body.textContent = greeter(user);

上一篇 下一篇

猜你喜欢

热点阅读