typescript入门
2018-08-03 本文已影响0人
我竟无言以对_1202
安装typescript
npm install -g typescript
在vscode中自动编译typescript
- 创建tsconfig.json文件
tsc --init
- 将下面代码复制到tsconfig.json文件中
{
"compilerOptions": {
"target": "es5",
"noImplicitAny": false,
"module": "amd",
"removeComments": false,
"sourceMap": false,
"outDir": "src/js"//你要生成js的目录
}
}
- 接下来就是在.ts文件中写typescript代码,完成之后点击菜单 任务-运行任务,点击tsc:构建-tsconfig.json
typescript基本数据类型
- Boolean
var isBool:boolean = false;
function tell(){
alert(isBool);
}
tell();
- Number
var num:number = 10;
console.log(num);
- String
var str:string = "帅哥";
function tell(){
str+="hello ";
alert(str);
}
tell();
- Array
// 第一种方式
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 枚举
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
- Any 不知道什么类型
有时候,我们会想要为那些在编程阶段还不清楚类型的变量指定一个类型。 这些值可能来自于动态的内容,比如来自用户输入或第三方代码库。 这种情况下,我们不希望类型检查器对这些值进行检查而是直接让它们通过编译阶段的检查。 那么我们可以使用 any类型来标记这些变量:
var notsure:any =10;
var list:any[] = [1,"hello",false];
- void
当一个函数没有返回值时,你通常会见到其返回值类型是 void:
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());
- 修饰符
public
private
接口
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));
- 模块