目录
一、基础类型string、number、boolean、void、undefined、null的声明
七、内置对象:查询地址TypeScript/lib at main · microsoft/TypeScript · GitHub
最近在学习TypeScript记录一下学习过程。
一、基础类型string、number、boolean、void、undefined、null的声明
// 1. string(字符串) 类型声明
let str: string = 'anc'
let str: string = `123`
// 2.number(数字类型)类型的声明 可声明 普通数字、NaN、Infinity(无穷大)、和进制数
let num: number = 123
let numNaN: number = NaN
let numInfinity: number = Infinity // 无穷大
let numBinary: number = 0b1110 // 二进制
let numHex: number = 0xf00c // 十六进制
let octalHex: number = 0o756 // 八进制
// 3. boolean、Boolean(布尔值)类型声明。不能用new Boolean进行声明boolean,也不能用boolean声明new Boolean
let booleanType: boolean = true // 直接声明
let booleanType: boolean = Boolean(1) // 通过Boolean转化为true
let booleanType: Boolean = new Boolean(1) // new Boolean返回是一个boolean对象
// 4. void 类型用于声明undefined、null和没有返回值的函数
let un: void = undefined
let nu: void = null
function add():void {} // 声明没有返回值的函数
// 5. undefined、null类型声明。undefined、null是所有类型的子集可以赋值给其它类型
let un: undefined = undefined
let nu: null = null
// undefined、null和void的区别:void 不能赋值给其它类型 undefined 和null 可以
let str: string ='avb'
let v: void = null
let nu: null = null
str = v // × 不可以赋值
str = nu // √ 可以赋值
二、所有类型any、unkonwn
// 定义任意类型any
let a:any = 123
a = 'abc'
a = true
a = {}
a = []
// 定义任意类型unknown
let a: unknown = {c: 123}
let b: string = '123'
a = 'abc'
a = true
a = {}
a = []
b = a // error unknown类型不能赋值给其它类型
console.log(a.c) // error unknown不能使用内部的属性和方法
三、对象类型定义
// 基本声明
interfice Obj{
name: string
age: number
sex?: string // 可选属性声明
}
let obj:Obj = {
name: 'abc',
age: 123
}
let obj1:Obj = {
name: 'abc',
age: 123,
sex: '男'
}
// 同名合并声明
interfice Obj{
name: string
}
interfice Obj{
age: number
}
let obj:Obj = {
name: 'abc',
age: 123
}
// readonly 只读声明
interfece Obj {
readonly name: string
}
let obj:Obj = {
name: "张三"
}
obj.name = '李四' // error 不能赋值
// propName 未知属性定义,用于对象可能存在不知道的属性的时候,如后端返回的对象
// 注:propName定义的类型 必须包含整个对象的所有类型
interfece Obj {
name: string
[propName: string]: any // 任意类型
}
interfece Obj1 {
[propName: string]: string
name: string, // success
age: number // error propName类型为string不包含number类型
}
let obj:Obj = {
name: 'abc',
phone: '132123456'
}
// 接口的定义
interfece Obj {
add(): number,
subtract(): void
}
let obj: Obj = {
add: ():number => {
return 123
}
subtract: () => {} // void任意类型不需要返回值
}
// 组合继承
interfece A{
name: string
}
interfece B extends A{
age: number
}
let p:B = {
name: 'abc'
age: 123
}
四、数组类型定义
// 基本定义方式
let arrNum: number[] = [1, 2, 3] // 数字类型数组
let arrStr: string[] = ['卧槽', '真厉害'] // 字符串类型数组
let arrBool: boolean[] = [true, false] // boolean类型数组
let arrBool: any[] = [1, '沙雕', true, {}] // 任意类型数组
let arrBool: any[][][] = [ [[]], [[]], [[]] ] // 多维数组
// 泛型定义
let arrNum: Array<number> = [1, 2, 3] // 数字类型数组
let arrStr: Array<string> = ['卧槽', '是真猛'] // 字符串类型数组
let arrBool: Array<boolean> = [true, false] // boolean类型数组
let arrBool: Array<any> = [1, '沙雕', true, {}] // 任意类型数组
let arrBool: Array<Array<Array<any>>>[][][] = [ [[]], [[]], [[]] ] // 多维数组
// 类数组IArguments
function a(...args: any): void {
cosnole.log(arguments)
let arr: IArguments = arguments
}
a(1,2,3)
// IArguments 内部实现
interfece IArguments {
[index: number]: any;
length: number;
callee: Function;
}
五、数组类型定义
// 基本的定义
const add = function(name: sting, sex: number): string {
return name + number
}
let a = fn("张三", 30)
// 默认传参: 有默认参数即可以不传参
const add = function(name: sting, sex: number = 1): string {
return name + number
}
let a = fn("张三")
// 可选参数
const add = function(name: sting, sex?: number): string {
return name + number
}
let a = fn("张三")
let b = fn("张三", 123)
// interfece定义
interfece P {
name: string
sex: number
}
const add = function(p:P): string {
return p.name + p.number
}
add ({name: '张三', sex: 1})
// 重载函数
function fn(params: number):void // 规则1
function fn(params: string, params1: number): void // 规则2
function fn(params: any, params1?: any):any {
// 注 由于第一个规则没有params1 所以params1为一个可选参数
return params + params1
}
fn(1) // 自动遵循第一个规则
fn('1', 123) // 自动遵循第二个规则
六、联合类型、 类型断言、交叉类型
// 联合类型
let p: number | string = 0
p = 'adv'
// 交叉类型
interface P{
name: string
}
iterface P1 {
age: number
}
const popleInfo = (a: P & P1): void {
console.log(a)
}
popleInfo({
name: '小王',
age: 1
})
// 类型断言
let fn = function(num: number | string): void {
// 由于num可能是number,numebr没有length 所以我们断言成string
console.log((num as string).length)
}
fn('123456')
七、内置对象:查询地址
const regexp: RegExp = /\d/ // 正则对象
const date: Date = new Date() // 时间对象
const error: Error = new Error('发生错误了') // 错误对象
const domLost: NodeList = document.querySelectAll('div') // dom列表
const body: HTMLElement = document.body // HTMLElement
function promise():Promise<number> { // Promise对象
return new Promise<number>((resolve, reject) => {
resolve(1)
})
}
promise().then(res => {
console.log(res)
})
// HTML标签对照表
"a": HTMLAnchorElement;
"abbr": HTMLElement;
"address": HTMLElement;
"area": HTMLAreaElement;
"article": HTMLElement;
"aside": HTMLElement;
"audio": HTMLAudioElement;
"b": HTMLElement;
"base": HTMLBaseElement;
"bdi": HTMLElement;
"bdo": HTMLElement;
"blockquote": HTMLQuoteElement;
"body": HTMLBodyElement;
"br": HTMLBRElement;
"button": HTMLButtonElement;
"canvas": HTMLCanvasElement;
"caption": HTMLTableCaptionElement;
"cite": HTMLElement;
"code": HTMLElement;
"col": HTMLTableColElement;
"colgroup": HTMLTableColElement;
"data": HTMLDataElement;
"datalist": HTMLDataListElement;
"dd": HTMLElement;
"del": HTMLModElement;
"details": HTMLDetailsElement;
"dfn": HTMLElement;
"dialog": HTMLDialogElement;
"div": HTMLDivElement;
"dl": HTMLDListElement;
"dt": HTMLElement;
"em": HTMLElement;
"embed": HTMLEmbedElement;
"fieldset": HTMLFieldSetElement;
"figcaption": HTMLElement;
"figure": HTMLElement;
"footer": HTMLElement;
"form": HTMLFormElement;
"h1": HTMLHeadingElement;
"h2": HTMLHeadingElement;
"h3": HTMLHeadingElement;
"h4": HTMLHeadingElement;
"h5": HTMLHeadingElement;
"h6": HTMLHeadingElement;
"head": HTMLHeadElement;
"header": HTMLElement;
"hgroup": HTMLElement;
"hr": HTMLHRElement;
"html": HTMLHtmlElement;
"i": HTMLElement;
"iframe": HTMLIFrameElement;
"img": HTMLImageElement;
"input": HTMLInputElement;
"ins": HTMLModElement;
"kbd": HTMLElement;
"label": HTMLLabelElement;
"legend": HTMLLegendElement;
"li": HTMLLIElement;
"link": HTMLLinkElement;
"main": HTMLElement;
"map": HTMLMapElement;
"mark": HTMLElement;
"menu": HTMLMenuElement;
"meta": HTMLMetaElement;
"meter": HTMLMeterElement;
"nav": HTMLElement;
"noscript": HTMLElement;
"object": HTMLObjectElement;
"ol": HTMLOListElement;
"optgroup": HTMLOptGroupElement;
"option": HTMLOptionElement;
"output": HTMLOutputElement;
"p": HTMLParagraphElement;
"picture": HTMLPictureElement;
"pre": HTMLPreElement;
"progress": HTMLProgressElement;
"q": HTMLQuoteElement;
"rp": HTMLElement;
"rt": HTMLElement;
"ruby": HTMLElement;
"s": HTMLElement;
"samp": HTMLElement;
"script": HTMLScriptElement;
"section": HTMLElement;
"select": HTMLSelectElement;
"slot": HTMLSlotElement;
"small": HTMLElement;
"source": HTMLSourceElement;
"span": HTMLSpanElement;
"strong": HTMLElement;
"style": HTMLStyleElement;
"sub": HTMLElement;
"summary": HTMLElement;
"sup": HTMLElement;
"table": HTMLTableElement;
"tbody": HTMLTableSectionElement;
"td": HTMLTableCellElement;
"template": HTMLTemplateElement;
"textarea": HTMLTextAreaElement;
"tfoot": HTMLTableSectionElement;
"th": HTMLTableCellElement;
"thead": HTMLTableSectionElement;
"time": HTMLTimeElement;
"title": HTMLTitleElement;
"tr": HTMLTableRowElement;
"track": HTMLTrackElement;
"u": HTMLElement;
"ul": HTMLUListElement;
"var": HTMLElement;
"video": HTMLVideoElement;
"wbr": HTMLElement;
// svg对照表
"a": SVGAElement;
"animate": SVGAnimateElement;
"animateMotion": SVGAnimateMotionElement;
"animateTransform": SVGAnimateTransformElement;
"circle": SVGCircleElement;
"clipPath": SVGClipPathElement;
"defs": SVGDefsElement;
"desc": SVGDescElement;
"ellipse": SVGEllipseElement;
"feBlend": SVGFEBlendElement;
"feColorMatrix": SVGFEColorMatrixElement;
"feComponentTransfer": SVGFEComponentTransferElement;
"feComposite": SVGFECompositeElement;
"feConvolveMatrix": SVGFEConvolveMatrixElement;
"feDiffuseLighting": SVGFEDiffuseLightingElement;
"feDisplacementMap": SVGFEDisplacementMapElement;
"feDistantLight": SVGFEDistantLightElement;
"feDropShadow": SVGFEDropShadowElement;
"feFlood": SVGFEFloodElement;
"feFuncA": SVGFEFuncAElement;
"feFuncB": SVGFEFuncBElement;
"feFuncG": SVGFEFuncGElement;
"feFuncR": SVGFEFuncRElement;
"feGaussianBlur": SVGFEGaussianBlurElement;
"feImage": SVGFEImageElement;
"feMerge": SVGFEMergeElement;
"feMergeNode": SVGFEMergeNodeElement;
"feMorphology": SVGFEMorphologyElement;
"feOffset": SVGFEOffsetElement;
"fePointLight": SVGFEPointLightElement;
"feSpecularLighting": SVGFESpecularLightingElement;
"feSpotLight": SVGFESpotLightElement;
"feTile": SVGFETileElement;
"feTurbulence": SVGFETurbulenceElement;
"filter": SVGFilterElement;
"foreignObject": SVGForeignObjectElement;
"g": SVGGElement;
"image": SVGImageElement;
"line": SVGLineElement;
"linearGradient": SVGLinearGradientElement;
"marker": SVGMarkerElement;
"mask": SVGMaskElement;
"metadata": SVGMetadataElement;
"mpath": SVGMPathElement;
"path": SVGPathElement;
"pattern": SVGPatternElement;
"polygon": SVGPolygonElement;
"polyline": SVGPolylineElement;
"radialGradient": SVGRadialGradientElement;
"rect": SVGRectElement;
"script": SVGScriptElement;
"set": SVGSetElement;
"stop": SVGStopElement;
"style": SVGStyleElement;
"svg": SVGSVGElement;
"switch": SVGSwitchElement;
"symbol": SVGSymbolElement;
"text": SVGTextElement;
"textPath": SVGTextPathElement;
"title": SVGTitleElement;
"tspan": SVGTSpanElement;
"use": SVGUseElement;
"view": SVGViewElement;
八、class类
// 定义this变量,需要提前类型声明。 声明了变量就需要使用
class Person {
name: string // 声明类型
age: number
sex: string // 声明了 没有使用会报错。 可以设置一个默认值
constructor(name:string, age: number) {
this.name = name // 定义变量
this.age = age
}
}
// public、private、protected属性
class Person {
age: number // 不写, 默认声明就为public
public name: string // public属性用于定义外部可以访问的属性
private sex:string = '男' // 私有属性 子类,外部都无法访问
protected: height: string = '150cm' // 外部无法访问,但是子类可以访问、使用
constructor(name) {
this.name = name
this.age = age
}
}
class Wang extends Person {
constructor() {
super("猪猪")
console.log(this.height) // 150cm
console.log(this.sex) // error
}
}
let p: new Person("猪猪", 18)
console.log(p.name, p.age) // 猪猪 18
console.log(p.height) // error
console.log(p.sex) // error
/**
* static 静态属性
* 1. 通过类名直接进行访问。无需new
* 2. 静态函数内部可以通过this访问其它的静态属性、静态函数
* 3. 静态属性无法通过this直接访问
* 4. 静态函数只可以通过类名直接调用, 不能通过this调用
*/
class Person {
name: string = "狗子"
static n: string
constructor() {
this.n = 'aaa'
this.add() // error 规则4
Person.add() // 123 规则4
}
static add(){
console.log(this.n) // 'aaa' 规则 1
console.log(this.name) // error 规则3
return 123
}
}
console.log(Person.n) // 规则1
console.log(Person.add()) // 规则1
// interfece定义class类, 通过implements
interfeac P {
add(count: number): number
}
interfeac P1 {
subtract(count: number): number
}
class Person implements P, P1 {
add(count: number) {
return count
}
add(subtract: number) {
return count
}
}