Typescript

Typescript

TypeScript是JavaScript的超集,这意味着其完全兼容JS。

TypeScript类型注解

类型注解:轻量级的为函数或变量添加约束的方式
~ 语法 let title:string
~ 常用类型:string,number,boolean,string[],[string,number],any,any[],object
~ 枚举类型enum
声明 enum Color{Red,Green,Blue}
使用 Color.Blue

let tt: any;
tt = '1100';

const t1 = '123';

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

~ 函数类型注解
参数类型 function greeting(msg:string){}
返回值类型
function warning():void{}
function plus(a,b):number{}
~ 类型推论:如果直接给变量赋值,不必设置类型注解,编译器会进行类型推断

function f(): void {
  alert('112334');
}

function  add(a: number, b: number): number {
  return a + b;
}
console.log(add(1 , 2));

- 接口:约束类型的结构。
~ 声明接口 interface Person{ firstName:string;lastName:string;toString():string; }
~ 实现接口 只需和接口声明兼容即可

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

function f1(person: Person): string {
  return person.firstName + ' ' + person.lastName;
}
const user1 = { firstName: 'zz', lastName: '22'};
console.log(f1(user1));

- 类:TypeScript支持JavaScript的新特性,比如支持基于类的面向对象编程
~ 声明类
class Student{
fullName: string;

contructor(){}
}

new Student()

class Student {
  fullName: string;
  constructor(public firstName: string , public lastName: string) {
    this.fullName = firstName + ' ' + lastName;
  }
  toString(): string{
    return this.fullName;
  }
}
const stuInstance = new Student('zhan' , 'san');
console.log(stuInstance.toString());
console.log(stuInstance.fullName);
console.log(stuInstance.firstName + ' ' + stuInstance.lastName);

- 函数
~ TypeScript中函数如果声明了参数,则这些参数是必须的
~ 可选参数
function buildName(firstName:string,lastName?:string)

* 注意:可选参数必须放在必须参数后面

~ 参数默认值
function buildName(firstName:string,lastName:string = 'Smith')

function buildName(firstName: string , lastName: string): string {
  return `$firstName $lastName`;
}

- 模块:A = B + C
~ 导入 import 导出 export
~ 导出
* 具名导出
export const title=''

* 默认导出
export default class{...}
注意:一个文件中默认导出只能有一个

* 导出语句
export {a,b,c}

~ 导入
* 具名导入
import {title} from './type-annotation'

* 默认导入
import Student from './type-annotation'

原文地址:https://www.cnblogs.com/youguess/p/13452220.html