当前位置:网站首页>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
边栏推荐
猜你喜欢
随机推荐
Letter combination of LeetCode2 phone number
Seq2Seq模型PyTorch版本
没学好统计学的下场
13.56MHZ刷卡芯片CI521兼容cv520/ci520支持A卡B卡MIFARE协议
【我的电赛日记(二)】ADF4351锁相环模块
boost库智能指针
PyTorch⑥---卷积神经网络_池化层
Makefile容易犯错的语法
PyTorch②---transforms结构及用法、常见的Transforms
CS4398音频解码替代芯片DP4398完全兼容DAC解码
DP1101兼容CC1101是SUB1GHz无线收发芯片应用于智能家居
win10怎么设置不睡眠熄屏?win10设置永不睡眠的方法
Win10系统设置application identity自动提示拒绝访问怎么办
Bert系列之 Transformer详解
FP6296锂电池升压 5V9V12V内置 MOS 大功率方案原理图
How to set the win10 taskbar does not merge icons
针对多轮推理分类问题的软标签构造方法
arm ldr系列指令
Win11系统找不到dll文件怎么修复
牛客刷题汇总(持续更新中)









