TypeScript
1、继承
function add(x:number,z?:number):number{}
// 可索引类型
interface RandomMap {
[propName: string]: string;
}
const test:RandomMap{
a:'1',
b:'2'
}
// 类数组
interface LikeArray {
[index: number]: string;
}
const likeArray:LikeArray=['1','2','3']
//函数添加属性
interface FunctionWithProps {
(x: number): number;
name: string;
}
const a:FunctionWithProps=(x:number)=>{
return x
}
a.name='abc'
class Animal {
//修饰符
private|public|protected name: string
constructor(name: string) {
this.name = name
}
run() {
return `${this.name} is running`
}
}
const snake = new Animal('haha')
snake.run()
//继承
class Dog extends Animal {
//多态
bark() {
return `${this.name} is bark`
}
}
2、实现
interface ClockInterface {
currentTime: number
alter(): void
}
interface GameInterface {
play: void
}
interface ClockStatic {
//构造函数
new (h: number, m: number): void
//静态属性
time: number
}
//实现接口
const Clocl: ClockStatic = class Clock implements ClockInterface {
constructor(h: number, m: number) {}
static time: 10
currentTime: number
alter(): void {
throw new Error('Method not implemented.')
}
}
//实现多接口
class CellPhone implements ClockInterface, GameInterface {
play: void
currentTime: number
alter(): void {
throw new Error('Method not implemented.')
}
}
3、泛型
//如果是string,返回就有string的特性
//如果是number,返回就有number的特性
function echo<T>(arg: T): T {
return arg
}
const res: number = echo(12)
function swap<T, U>(tuple: [T, U]): [U, T] {
return [tuple[1], tuple[0]]
}
const res1 = swap(['string', 123])
interface GithubResp {
name: string
count: number
}
function withApi<T>(url: string): Promise<T> {
return fetch(url).then(res => res.json())
}
withApi<GithubResp>('github.user').then(res => {
res.count
})
4、高级特性
type PersionResp = {
name: string
count: number
}
//相当于PersionResp的联合类型 获得type属性的键
type Keys = keyof PersionResp
//获得定义type属性的值
type nameType = PersionResp['name']
//?可选类型 p in Keys 遍历keys
type Test = { [p in Keys]?: PersionResp[p] }
//结果:
// type Test = {
// name?: string
// count?: number
// }
const str2 = '124' //因为const是常量,所以类型是124
let str1 = '123' //是变量 类型是string
function sum(a: number, b: number): number {
return a + b
}
//类型别名
type PlusType = (x: number, y: number) => number
let sum2: PlusType
sum2(1, 2)
interface IName {
name: string
}
type TPerson = IName & { age: number }
let person: TPerson = {
name: '1',
age: 1
}
//联合类型
let numberOrString: number | string
function getLength(input: number | string) {
//类型断言
const str = input as string
if (str.length) {
return str.length
} else {
const num = input as number
return num.toString().length
}
}
interface IWithLength {
length: number
}
//extends T中必须包含IWithLength的属性,这样就支持输出length,包括number、boolean
function echoWith<T extends IWithLength>(arg: T): T {
console.log(arg.length)
return arg
}
const arr = echoWith([1, 2, 3])
const str = echoWith('123')
const obj = echoWith({ length: 1, width: 12 })
type NonType<T> = T extends null | undefined ? never : T
let demo1: NonType<number> //类型是T
let demo2: NonType<null> //类型是never
声明文件
jQuery('#id')
//如果没有声明文件,会直接报错,针对一些第三包不支持ts的情况,可以写声明文件,默认全局使用
declare var jQuery: (selector: string) => any
举例:
function myFetch(url, method, data) {
return fetch(url, {
body: data ? JSON.stringify(data) : '',
method
}).then(res => res.json())
}
myFetch.get = (url, data) => {
return myFetch(url, 'get', data)
}
myFetch.post = (url, data) => {
return myFetch(url, 'post', data)
}
export default myFetch
type HttpMethod = 'GET' | 'POST' | 'DELETE' | 'PATCH'
declare function myFetch<T = any>(url: string, method: HttpMethod, data?: any): Promise<T>
//namespace 里面是定义的方法
declare namespace myFetch {
const get: <T=any>(url: string, data?: any) => Promise<T>
const post: <T=any>(url: string, data?: any) => Promise<T>
}
//导出 可以作为第三方插件使用
export = myFetch
注意:需要将ts、d.ts放在@types,作为第三方插件使用,否则使用泛型会报错
//res 类型是any
myFetch('test', 'GET', { name: 'hello' }).then(res => {})
//res number
myFetch<number>('test', 'GET', { name: 'hello' }).then(res => {})
//any
myFetch.get('test', 'data').then(res => {})
type CopyActionOptions = {
container?: Element
}
type Response = 'success' | 'error'
declare class ClipboardJS {
constructor(selector: string, options: ClipboardJS.Options)
on(type: Response, handler: (e: ClipboardJS.Event) => void): this
destory(): void
}
declare namespace ClipboardJS {
interface Options {
action?(elem: Element): Action
target?(elem: Element): Element
text?(elem: Element): string
container?: Element
}
}
export = ClipboardJS