vlambda博客
学习文章列表

深入理解TypeScript——第一章:上手篇

怎么定义TypeScript呢?TypeScript是一个工具 是一个编译器

1、编译代码

TypeScript,通过它的能力,默认使用tsc命令,可以根据.ts为后缀名的文件生成一个新的js文件

2、类型注解

TypeScript里的类型注解是一种轻量级的为函数或变量添加约束的方式。TypeScript提供了静态的代码分析,它可以分析代码结构和提供的类型注解。

function doSth(who: string): string {
return "I want to say hello to " + who;
}

let who = 'her';

const doWhat = doSth(who);

console.log('doWhat:', doWhat)
// doWhat: I want say hello to her

这里插个题外话,如果部分语法产生error的话,要考虑tsconfig.json这样的配置文件(比如lib部分)是否支持了你需要的Javascript规范,如果不支持的话,建议使用polyfill

3、接口

允许我们在实现接口时候只要保证包含了接口要求的结构就可以

interface Girl {
hair: string;
face: string;
}

function describe(girl: Girl): string {
let words = 'she has '
let decs = Object.entries(girl)
let len = decs.length

for (let i = 0; i < len; i++) {
const [where, like] = decs[i];
words+=(like + ' ' + where)
words+=(i === len - 1 ? '' : ' and ')
}
return words
}

const sentence = describe({
hair: 'long',
face: 'beautiful'
})

console.log('sentence:', sentence);
// sentence: she has long hair and beautiful face

4、类

支持基于类的面向对象编程
在构造函数的参数上使用public等同于创建了同名的成员变量

class She {
praise: string;
constructor(public hair: string, public face: string) {
// this.praise = hair + ' hair' + " and " + face + ' face';
}
}

interface Girl {
hair: string;
face: string;
}

function describe(girl: Girl): string {
let words = 'she has '
let decs = Object.entries(girl)
let len = decs.length

for (let i = 0; i < len; i++) {
const [where, like] = decs[i];
words+=(like + ' ' + where)
words+=(i === len - 1 ? '' : ' and ')
}
return words
}

const she = new She('long', 'beautiful')

const sentence = describe(she)

console.log('sentence', sentence);

上面这段代码通过ts编译,成为了下面这段代码

var She = /** @class */ (function () {
function She(hair, face) {
this.hair = hair;
this.face = face;
// this.praise = hair + ' hair' + " and " + face + ' face';
}
return She;
}());
function describe(girl) {
var words = 'she has ';
var decs = Object.entries(girl);
var len = decs.length;
for (var i = 0; i < len; i++) {
var _a = decs[i], where = _a[0], like = _a[1];
words += (like + ' ' + where);
words += (i === len - 1 ? '' : ' and ');
}
return words;
}
var she = new She('long', 'beautiful');
var sentence = describe(she);
console.log('sentence', sentence);

看起来,只是多了一些特殊的注释,以及修改了一些局部变量名,所以ts主要的功能其实是为了规范书写,校验传入参数是否正确,从而实现更高质量的代码!