当前位置:网站首页>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
边栏推荐
- Seq2Seq模型PyTorch版本
- 基于GPT的隐变量表征解码结构
- 利用红外-可见光图像数据集OTCBVS打通图像融合、目标检测和目标跟踪
- 【深度学习中的损失函数整理与总结】
- 机器学习和深度学习中的梯度下降及其类型
- Win10电脑不能读取U盘怎么办?不识别U盘怎么解决?
- The problem that UIWindow's makeKeyAndVisible does not call viewDidLoad of rootviewController
- Detailed explanation of RecyclerView series article directory
- “自主可控”的正确姿势
- 基于无监督医学图像配准论文(1)
猜你喜欢
随机推荐
FP7195芯片PWM转模拟调光至0.1%低亮度时恒流一致性的控制原理
文本匹配任务
还是别看学位论文
PyTorch①---加载数据、tensorboard的使用
Binder机制(下篇)
FP7195大功率零压差全程无频闪调光DC-DC恒流芯片(兼容调光器:PWM调光,无极调光,0/1-10V调光)
【我的电赛日记(三)】STM32学习笔记与要点总结
Makefile容易犯错的语法
FP7128内置MOS降压恒流调光深度0.01%高辉共阳调光方案
The problem that UIWindow's makeKeyAndVisible does not call viewDidLoad of rootviewController
2.4G无线小模块CI24R1超低成本
jest测试,组件测试
LLVM系列第十七章:控制流语句for
win10系统更新错误代码0x80244022怎么办
内存申请(malloc)和释放(free)之下篇
vscode镜像
针对多轮推理分类问题的软标签构造方法
没学好统计学的下场
boost库智能指针
Win10无法连接打印机怎么办?不能使用打印机的解决方法









