当前位置:网站首页>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⑩---卷积神经网络_一个小的神经网络搭建
- 内存申请(malloc)和释放(free)之下篇
- 流,向量场,和微分方程
- 【我的电赛日记(完结)---2021全国大学生电子设计竞赛全国一等奖】A题:信号失真度测量装置
- LLVM系列第八章:算术运算语句Arithmetic Statement
- FP7128内置MOS降压恒流调光深度0.01%高辉共阳调光方案
- 实战美团Nuxt +Vue全家桶,服务端渲染,邮箱验证,passport鉴权服务,地图API引用,mongodb,redis等技术点
- LLVM系列第七章:函数参数Function Arguments
- Win10电脑需要安装杀毒软件吗?
- 【使用Pytorch实现ResNet网络模型:ResNet50、ResNet101和ResNet152】
猜你喜欢
随机推荐
Win10系统设置application identity自动提示拒绝访问怎么办
没学好统计学的下场
DP4301无线收发SUB-1G芯片兼容CC1101智能家居
发布模块到npm应该怎么操作?及错误问题解决方案
“非图灵完备”到底意味着什么
Win10电脑不能读取U盘怎么办?不识别U盘怎么解决?
FP7122降压恒流内置MOS耐压100V共正极阳极PWM调光方案原理图
镜像法求解接地导体空腔电势分布问题
内存申请(malloc)和释放(free)之下篇
【我的电赛日记(一)】HMI USART串口屏
【我的电赛日记(完结)---2021全国大学生电子设计竞赛全国一等奖】A题:信号失真度测量装置
单端K总线收发器DP9637兼容L9637
Pytorch(16)---搭建一个完整的模型
SQL的通用语法和使用说明(图文)
A clean start Windows 7?How to load only the basic service start Windows 7 system
FP7195大功率零压差全程无频闪调光DC-DC恒流芯片(兼容调光器:PWM调光,无极调光,0/1-10V调光)
Win10上帝模式干嘛的?Win10怎么开启上帝模式?
How to set the win10 taskbar does not merge icons
Letter combination of LeetCode2 phone number
ARMv8虚拟化