安裝
Typescript的基本介紹可以自行百度
centos虛擬機中可以完整的體驗, virtualbox安裝開發版本,選擇開發工具項,否則增強功能無法安裝【提示kernel 頭文件缺失,yum安裝后仍是無效】
一些具體的網址
https://github.com/Microsoft/TypeScriptSamples
http://www.typescriptlang.org/
http://stackoverflow.com/questions/30536840/typescript-how-to-reference-jquery-easyui-library
https://github.com/DefinitelyTyped/DefinitelyTyped
由於typescript基於node的環境,因此需要安裝nodejs npm ,然后安裝依賴的包,
直接鏈接國際站點太慢,加速npm包
編輯 ~/.npmrc 加入下面內容
registry = https://registry.npm.taobao.org
sudo yum install nodejs
sudo yum install npm
npm install -g typescript
如上即安裝了typescript,命令行下輸入tsc -h可以看看
在Java項目中擁抱Nodejs — 使用gruntjs編譯typescript,並將生成的js合並、壓縮
http://www.tuicool.com/articles/aY3IVz
如果使用了idea專業版,直接集成了typescript,使用起來更簡單,只要配置了項目文件就行,typescript的項目文件tsconfig.json類似如下,根據自己的需要設置即可
{
"compilerOptions": {
"target": "es5",
"noImplicitAny": false,
"module": "commonjs",
"removeComments": true,
"sourceMap": true,
"outDir": "js/dev/",
"sourceRoot": "ts/"
}
//"include":[
// "ts"
// ],
//"exclude": [
// "js"
// ]
}
基本類型
//基本類型
let flag: boolean = false;
const pi = 3.1415;
var n: number = 1;
var s: string = 'hello';
enum Color { Red, Green };
var bns: number[] = [1, 2, 3];
var ar: Array<number> = [1, 2]
//any
var list2 = [1, true, "free"];
//
var x = null;
//union type
var u: string | number;
u = "OK";
u = 42;
//遍歷
for(b1 in bns){
console.log(b1);
}
list2.forEach(e => {
console.log(e);
});
//
var tuple = { 'k1': 1, 'k2': (s: string): number => { console.log(s); return 100; } }
console.log(tuple["k2"]("hello world"));
interface IUserInfo {
age: any;//定義一個任何變量的 age.
userName: string;//定義一個 username.
width?: number; //可選屬性
}
//類和接口 默認作用域 public
interface IClock {
currentTime: Date;
setTime(d: Date);
}
//--實現 IClock 接口
class Clock implements IClock {
currentTime: Date;
//--構造函數方法
constructor(h: number, m: number) {
this.setTime(new Date());
}
setTime(d: Date) {
this.currentTime = d;
}
}
let clk = new Clock(10, 10);
console.log(clk.currentTime);
class Person {
constructor(u: string) {
}
}
class Student1 extends Person {
constructor(username: string) {
super(username);
}
}
class Grid {
static origin = { x: 0, y: 0 };//不需要實例化就能訪問
calculateDistanceFromOrigin(point: { x: number; y: number; }) {
var xDist = (point.x - Grid.origin.x);
var yDist = (point.y - Grid.origin.y);
return Math.sqrt(xDist * xDist + yDist * yDist) / this.scale;
}
constructor(public scale: number) { }
}
//.net語言的get set
var passcode = "secret passcode";
class Employee {
private _fullName: string;
get fullName(): string {
return this._fullName;
}
set fullName(newName: string) {
if (passcode && passcode == "secret passcode") {
this._fullName = newName;
} else {
console.error("Error");
}
}
}
//定義合並
interface Box {
height: number;
width: number;
}
interface Box {
scale: number;
}
var box: Box = { height: 5, width: 6, scale: 10 }
module Animals {
export class Zebra { }
}
module Animals {
export interface Legged { numberOfLegs: number; }
export class Dog { }
}
var buildName1 = (firstName: string, lastName?: string) => {
if (lastName) {
return `${firstName} ${lastName}`;
} else {
return firstName;
}
};
var b1 = buildName1("a", "b");
console.log(n);
function buildName(firstName: string, ...restOfName: string[]) {
return `${firstName} ${restOfName.join(" ")}`;
}
var emplyeeName = buildName("lai", "xiao", "chai", "yun");
console.log(emplyeeName);
var deck = {
suits: ["hearts", "spades", "clubs", "diamonds"],
cards: Array(52),
//要想在函數內使用“this”,內層使用箭頭函數,外層使用正常函數
createCardPicker: function () {
return () => {
var pickedCard = Math.floor(Math.random() * 52);
var pickedSuit = Math.floor(pickedCard / 13);
return { suit: this.suits[pickedSuit], card: pickedCard % 13 };
}
}
}
var cardPicker = deck.createCardPicker();
var pickedCard = cardPicker();
console.log(`card: ${pickedCard.card} of ${pickedCard.suit}`);
function identity<T>(arg: T): T {
return arg;
}
var output = identity<string>("string");
console.log(output);
class GenericNumber<T>{
zeroValue: T;
add: (x: T, y: T) => T;
fuck(x) {
return x + 1;
}
}
var myGenericeNumber = new GenericNumber<number>();
myGenericeNumber.zeroValue = 0;
interface Lengthwise {
length: number;
}
function logginIdentity<T extends Lengthwise>(arg: T): T {
console.log(arg.length);
return arg;
}
interface Fullname {
[index: number]: string;
}
interface Firstname {
[index: string]: string;
}
var myName: Fullname = ["lai", "chuanfeng"];
var myFirstname: Firstname = { "firstname": "lai" };
console.log(myName[0]);
interface Account {
add(x: number): void;
}
function account(): Account {
return {
add(x) { ++x }
}
}
var a = account();
a.add(5);
//自動類型推導和提示
function langsvr(){
return {'a':'1', 'b':2};
}
langsvr().a;
//自動的any類型
var fn = (a, b) => { return a + b };
console.log(fn(1, 2));
console.log(fn("1", "2"));
console.log(fn(1, "2"));
定義
和已有Javascript js交互的例子
interface JQuery {
text(content: string);
}
interface JQueryStatic {
get(url: string, callback: (data: string) => any);
(query: string): JQuery;
}
declare var $: JQueryStatic;
$.get("http://mysite.org/divContent",
function (data: string) {
$("div").text(data);
}
);
The 'JQueryStatic' interface references another interface: 'JQuery'. This interface represents a collection of one or more DOM elements.
The jQuery library can perform many operations on such a collection, but in this example the jQuery client only needs to know that it can set the text content of each jQuery element in a collection by passing a string to the 'text' method.
The 'JQueryStatic' interface also contains a method, 'get', that performs an Ajax get operation on the provided URL and arranges to invoke the provided callback upon receipt of a response.
(query: string): JQuery;
The bare signature indicates that instances of the interface are callable. This example illustrates that
TypeScript function types are just special cases of TypeScript object types. Specifically, function types are object types that contain one or more call signatures.
內置的Javascipt的類型支持
declare var document;
document.title = "Hello";
// Ok because document has been declared
In the case of 'document', the TypeScript compiler automatically supplies a declaration, because
TypeScript by default includes a file 'lib.d.ts' that provides interface declarations for the built-in JavaScript library as well as the Document Object Model
typescript編譯器內置的定義文件
cancellationToken.js lib.es2017.object.d.ts
lib.dom.d.ts lib.es2017.sharedmemory.d.ts
lib.dom.iterable.d.ts lib.es5.d.ts
lib.d.ts lib.es6.d.ts
lib.es2015.collection.d.ts lib.scripthost.d.ts
lib.es2015.core.d.ts lib.webworker.d.ts
lib.es2015.d.ts protocol.d.ts
lib.es2015.generator.d.ts README.md
lib.es2015.iterable.d.ts tsc.js
lib.es2015.promise.d.ts tsserver.js
lib.es2015.proxy.d.ts tsserverlibrary.d.ts
lib.es2015.reflect.d.ts tsserverlibrary.js
lib.es2015.symbol.d.ts typescript.d.ts
lib.es2015.symbol.wellknown.d.ts typescript.js
lib.es2016.array.include.d.ts typescriptServices.d.ts
lib.es2016.d.ts typescriptServices.js
lib.es2017.d.ts typingsInstaller.js