当前位置:网站首页>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
边栏推荐
- 【使用Pytorch实现ResNet网络模型:ResNet50、ResNet101和ResNet152】
- Win11 computer off for a period of time without operating network how to solve
- 2020-02-06-快速搭建个人博客
- FP7195降压恒流PWM转模拟调光零压差大功率驱动方案原理图
- Win10 cannot directly use photo viewer to open the picture
- LORA芯片ASR6601支持M4内核的远距离传输芯片
- Mysql connection error solution
- Publish module to NPM should be how to operate?Solutions to problems and mistake
- LLVM系列第四章:逻辑代码块Block
- FP7195大功率零压差全程无频闪调光DC-DC恒流芯片(兼容调光器:PWM调光,无极调光,0/1-10V调光)
猜你喜欢
随机推荐
source /build/envsetup.sh和lunch)
“非图灵完备”到底意味着什么
基于GPT的隐变量表征解码结构
【使用Pytorch实现ResNet网络模型:ResNet50、ResNet101和ResNet152】
Bash shell位置参数
Pytorch(16)---搭建一个完整的模型
PyTorch(12)---损失函数和反向传播
FP7195降压恒流PWM转模拟调光零压差大功率驱动方案原理图
Win11怎么在右键菜单添加一键关机选项
Win11没有本地用户和组怎么解决
PyTorch⑦---卷积神经网络_非线性激活
TypeScript 快速进阶
define #使用
2.4G无线小模块CI24R1超低成本
Win10安装了固态硬盘还是有明显卡顿怎么办?
2021-10-14
最小树高度
boost库智能指针
How to add a one-key shutdown option to the right-click menu in Windows 11
Tensorflow常用函数