当前位置:网站首页>Fast advanced TypeScript
Fast advanced TypeScript
2022-08-02 15:22:00 【N.S.N】
Typescript
全局安装typescript npm install -g typescript
- typescript 文件后缀名以
.ts
结尾 - 把
ts
文件转为js
文件,使用命令行tsc ..ts
定义类型
// 原始数据类型
let isDone: boolean = false
let age: number = 20
let binaryNumber: number = 0b1111 // 二进制写法
let firstName: string = 'N.S.N'
let message: string = `hello ${
firstName}, age is ${
age}`
let u: undefined = undefined
let n: null = null
let num: number = undefined // undefined是所有类型的子类型
// 类型不确定
let notSure: any = 1
notSure = 'maybe it is a string'
notSure = true
notSure.myname
notSure.getName()
联合类型 let numberOrString: number | string = 245
Define array type
let arrOfNumbers: number[] = [1,5,6,7]
In the array value types must benumber,否则报错let arrOfNumber: Array<number> = [1,65,6,6,5]
泛型元祖(Tuple)类型:Also is one of belong to an array type
Tuple type refers to each position of the elements in the array specified type,Specify the type of position correspond to the elements in the array
let user: [string, number] = ['N.S.N', 20] // Position to and match them with the specified type
Interface 接口( 行为和动作的规范,对批量方法进行约束 )
- 对对象的形状(shape)进行描述
- 对类(class) 进行抽象
- Duck Typing (鸭子类型)
// As a formal contract,Specifies an object should grow
interface Person{
readonly id: number; // 只读属性 不可修改
name: string;
age?: number // ? 代表可选属性
}
let fang: Person = {
id: 1234,
name: 'N.S.N',
age: 20
}
函数是一等公民: Function and other types of object,都平等,可以作为参数,可以返回,对象属性,数组值,可以改变,可以赋值给其他变量
function add(x: number, y: number, z?: number): number{
return x + y + z
}
const add = function(x: number, y: number, z?: number): number{
return x + y + z
}
const add2: (x: number, y: number, z?: number)=>number = add
class Animal {
// 字段 − 字段是类里面声明的变量.字段表示对象的有关数据.
name: string;
static kind: string[] = ['hello', 'nice']
static isAnimal(a){
return a instanceof Animal
}
constructor(name: string) {
this.name = name
}
run() {
return `${
this.name} is running`
}
}
const snake = new Animal('fang')
console.log(snake.run())
console.log(Animal.kind) // 静态属性
console.log(Animal.isAnimal(snake)) // 静态方法
class Dog extends Animal {
bark() {
return `${
this.name} is barking`
}
}
const dog = new Dog('Tony')
console.log(dog.bark())
class Cat extends Animal {
constructor(name: string){
super(name)
console.log(this.name)
}
run( ){
return 'Meow, ' + super.run()
// Because the call of the parent class method and subclass methods repeat,所以使用super调用,否则使用this
}
}
const cat = new Cat('maomao')
console.log(cat.run())
修饰符 public private protected(A subclass can inherit,But for instance is private)
public :公有 在当前类里面、 子类 、类外面都可以访问
protected:保护类型 在当前类里面、子类里面可以访问 ,在类外部没法访问
private :私有 在当前类里面可以访问,子类、类外部都没法访问
readonly : 只读 在当前类里面、 子类 、类外面都可以访问 但不能修改
static : 静态方法、 类可以访问 、实例无法访问
类与接口
// 一种契约,Can constraint content
interface Radio {
name: string; // 也可以定义属性
switchRedio(): void; // Using the interface class must have the method,否则报错
}
interface Battery{
switchRedio(): void;
checkBatteryStatus();
}
class Car implements Radio{
name: string;
switchRedio() {
}
}
class Cellphone implements Battery{
switchRedio(){
}
checkBatteryStatus(){
}
}
枚举 enum
const enum direction {
// 常量枚举
Up = "Up",
Down = "Down",
Left = "Left",
Right = "Right",
}
console.log(direction.Up) // 'Up'
const value = 'Up'
if(value === direction.Up){
console.log('go up')
}
泛型 generics : 在定义函数、接口或者类的时候,不预先指定具体的类型,而是在使用的时候再指定类型.提高可重用性. (Can be seen as a placeholder)
function echo<T>(arg: T): T {
return arg
}
const result = echo('str')
function wrap<T, U>(tuple: [T, U]): [U, T]{
return [tuple[1], tuple[0]]
}
const result2 = wrap(['str', 123])
// 约束泛型
interface IWithLength {
length: number
}
// As long as the incoming parameters there arelength属性就可以
function echoWithLength<T extends IWithLength>(arg: T): T{
console.log(arg.length)
return arg
}
echoWithLength('str')
echoWithLength({
length: 14})
// 类
class Queue<T> {
private data = []
push(item: T){
return this.data.push(item)
}
pop(): T{
return this.data.shift()
}
}
const queue = new Queue<string>()
console.log(queue.push('ff'))
console.log(queue.pop().split(''))
// 接口
interface KeyPair<T, U>{
key: T,
value: U
}
let kp1: KeyPair<number, string> = {
key: 12,
value: 'fhx'
}
let kp1: KeyPair<string, boolean> = {
key: 'fang',
value: true
}
let arr: number[] = [1,23,3]
let arr: Array<number> = [1,6,6]
// 函数
interface IPlus<T> {
(a: T, b: T): T
}
function plus(a: number, b: number): number{
return a + b
}
let p: IPlus<number> = plus
函数别名
type sumType = (x: number, y: number) => number
function sum(x: number, y: number): number{
return x + y
}
const sum2: sumType = sum
type NameResolver = () => string // 不是箭头函数 ,Behind the arrow just function return value
type NumberOrResolver = string | NameResolver // 联合类型
function getName(a: NumberOrResolver): string{
if(typeof a === 'string'){
return a
}else{
return a()
}
}
类型断言
function getLength(input: number | string): number{
// const str = input as string
// if(str.length){
// return str.length
// }else{
// const number = input as number
// return number.toString().length
// }
if((<string>input).length){
return (<string>input).length
}else{
return (<number>input).toString().length
}
}
声明文件
- declare var jQuery = (selector: string) => any
边栏推荐
猜你喜欢
随机推荐
define #使用
LORA芯片ASR6505无线远距离传输8位MCU
基于深度学习的配准框架
ARMv8虚拟化
Win11电脑一段时间不操作就断网怎么解决
FP7195芯片PWM转模拟调光至0.1%低亮度时恒流一致性的控制原理
还是别看学位论文
Mysql连接错误解决
Pytorch(16)---搭建一个完整的模型
tensorflow实战之手写体识别
Binder机制(中篇)
循环神经网络RNN 之 LSTM
2021-10-14
DP4301无线收发SUB-1G芯片兼容CC1101智能家居
【深度学习中的损失函数整理与总结】
Win11 computer off for a period of time without operating network how to solve
“非图灵完备”到底意味着什么
How to reinstall Win7 system with U disk?How to reinstall win7 using u disk?
2022TI杯D题混沌信号产生实验装置
PHY6222蓝牙5.2支持MESH组网M0内核超低功耗