TypeScript语法

安装:npm install -g typescript

编译:tsc greeter.ts

类型注解:person:string

接口:

     interface Person{

         firstName:string;

         lastName:string

      }  

    调用:

         person:Person

         person.firstName

类:

     构造函数的参数上使用public等同于创建了同名的成员变量

class Student {
    fullName: string;
    constructor(public firstName, public middleInitial, public lastName) {
        this.fullName = firstName + " " + middleInitial + " " + lastName;
    }
}

 使用Gulp构建TypeScript,和如何在Gulp管道里添加BrowserifyuglifyWatchify。 它还包涵了 Babel的功能,通过使用Babelify

创建新目录:mkdir

mkdir proj
cd proj

初始化:

npm init

安装依赖项:

npm install -g gulp-cli

Browserify

把所有模块捆绑成一个JavaScript文件

安装Browserify,tsify(Browserify的一个插件)和vinyl-source-stream(将Browserify的输出文件适配成gulp能够解析的格式)

npm install --save-dev browserify tsify vinyl-source-stream

Watchify,Babel和Uglify

启动,编译

npm install --save-dev watchify gulp-util

 Uglify

npm install --save-dev gulp-uglify vinyl-buffer gulp-sourcemaps

 gulpfile文件

var gulp = require("gulp");
var browserify = require("browserify");
var source = require('vinyl-source-stream');
var tsify = require("tsify");
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var buffer = require('vinyl-buffer');
var paths = {
    pages: ['src/*.html']
};

gulp.task("copy-html", function () {
    return gulp.src(paths.pages)
        .pipe(gulp.dest("dist"));
});

gulp.task("default", ["copy-html"], function () {
    return browserify({
        basedir: '.',
        debug: true,
        entries: ['src/main.ts'],
        cache: {},
        packageCache: {}
    })
    .plugin(tsify)
    .bundle()
    .pipe(source('bundle.js'))
    .pipe(buffer())
    .pipe(sourcemaps.init({loadMaps: true}))
    .pipe(uglify())
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest("dist"));
});

获取声明文件

npm install -s @types/lodash

由模块导出

添加属性到exportsmodule.exports

module.exports.feedPets = function(pets) {
    // ...
}
export function feedPets(pets) {
    // ...
}

重写导出对象

var express = require("express");
var app = express();

声明一个使用 arguments对象的函数而不需要写出所有参数

***只在let命令所在的代码块内有效

连续添加属性

let options = {
    color: "red",
    volume: 11
};
interface Options { color: string; volume: number }

let options = {} as Options;
options.color = "red";
options.volume = 11;

anyObject,和{}

有一个Object类型的东西,你将不能够在其上调用toLowerCase()

any类型调用,构造它,访问它的属性,但会失去大多数TypeScript提供的错误检查和编译器支持。

严格的nullundefined检查

TypeScript把nullundefined当做属于任何类型

联合类型:number|null

假设有一个值TypeScript认为可以为nullundefined,但是你更清楚它的类型,你可以使用!后缀。:

foo!.length; // okay - 'foo!' just has type 'string[]'

显式赋值断言:来帮助类型系统识别类型,用在延迟初始化或重新初始化

let x!: number[];

数字分隔符

使用下划线(_)来对数字分组(就像使用逗号和点来对数字分组那样)。

基础类型

1.布尔值:boolean

let isDone: boolean = false;

2.数字:number

3.字符串:string,使用双引号( ")或单引号(')表示字符串

使用模版字符串,它可以定义多行文本和内嵌表达式。 这种字符串是被反引号包围( `),并且以${ expr }这种形式嵌入表达式

 4.数组:元素类型后面接上 []

5.元组 Tuple:表示一个已知元素数量和类型的数组

// Declare a tuple type
let x: [string, number];
// Initialize it
x = ['hello', 10]; // OK
// Initialize it incorrectly
x = [10, 'hello']; // Error

当访问一个越界的元素,会使用联合类型替代:

x[3] = 'world'; // OK, 字符串可以赋值给(string | number)类型

console.log(x[5].toString()); // OK, 'string' 和 'number' 都有 toString

x[6] = true; // Error, 布尔不是(string | number)类型

6.枚举

enum Color {Red, Green, Blue}
let c: Color = Color.Green;

7.Any(注意)

let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean

Any和Object的差别

Object类型的变量只是允许你给它赋任意值 - 但是却不能够在它上面调用任意的方法

let notSure: any = 4;
notSure.ifItExists(); // okay, ifItExists might exist at runtime
notSure.toFixed(); // okay, toFixed exists (but the compiler doesn't check)

let prettySure: Object = 4;
prettySure.toFixed(); // Error: Property 'toFixed' doesn't exist on type 'Object'.

 8.Null 和 Undefined

默认情况下nullundefined是所有类型的子类型。 就是说你可以把 nullundefined赋值给number类型的变量。

指定了--strictNullChecks标记,nullundefined只能赋值给void和它们各自

联合类型string | null | undefined

9.Never

永不存在的值的类型

总是会抛出异常或根本就不会有返回值的函数表达式或箭头函数表达式的返回值类型; 变量也可能是 never类型,当它们被永不为真的类型保护所约束时。

10.类型断言

类型断言有两种形式。 其一是“尖括号”语法:

let someValue: any = "this is a string";

let strLength: number = (<string>someValue).length;

另一个为as语法:

let someValue: any = "this is a string";

let strLength: number = (someValue as string).length;

11.let(注意)

尽可能地使用let来代替var

在一个嵌套作用域里引入一个新名字的行为称做屏蔽

readonly VS   const

 做为变量使用的话用 const,若做为属性则使用readonly

JSX

  1. 给文件一个 .tsx扩展名
  2. 启用 jsx选项

TypeScript具有三种JSX模式: preserve, react和 react-native,在代码生成阶段起作用

as操作符 类型断言符号

固有元素使用特殊的接口JSX.IntrinsicElements查找

declare namespace JSX {
    interface IntrinsicElements {
        foo: any
    }
}

<foo />; // 正确
<bar />; // 错误

无状态函数组件(SFC)

类组件

猜你喜欢

转载自blog.csdn.net/xuxuan1997/article/details/81266796