命令
- 查看版本:tsc -v
- 运行ts文件:tsc xx.ts
数据类型
// basic types
let isDone: boolean = false
let age: number = 10
let firstName: string = 'viking'
let message: string = `Hello, ${firstName}`
let u: undefined = undefined
let n: null = null
let num: string = null
let notSure: any = 4
notSure = 'maybe a string'
notSure = true
notSure.myName
notSure.getName()
// array
let arrOfNumbers: number[] = [1, 2, 3, 4]
arrOfNumbers.push(3)
// tuple
let user: [string, number] = ['viking', 20]
user = ['viking', 30]
// function
function add(x: number, y: number, z:number): number {
return x + y
}
//let result = add(2, 3)
let add2 = (x: number, y:number): number => {
return x + y
}
接口Interface
interface Person {
readonly id: number; // 只读
name: string;
age?: number; // 可选类型(可继承可不继承)
}
let viking: Person = {
name: 'viking',
age: 20,
id: 1
}
const sum = (x: number, y: number) => {
return x + y
}
interface ISum {
(x: number, y: number): number
}
const sum2: ISum = sum
interface RandomMap { // 可索引类型(对象随意传)
[propName: string]: string;
}
const test: RandomMap = {
a: 'hello',
b: 'test',
c: 'test'
}
interface LikeArray {
[index: number]: string
}
const likeArray: LikeArray = ['1', '2', '3']
// duck typing
interface FunctionWithProps {
(x: number): number;
name: string;
}
const a: FunctionWithProps = (x: number) => {
return x
}
a.name = 'abc'
类和接口
泛型基础知识
function echo<T>(arg: T): T { // 泛型,可识别可调用的方法。例如是整型,可调用整形下的方法
return arg
}
function swap<T, U>(tuple: [T, U]): [U, T] { // 返回调换位置
return [tuple[1], tuple[0]]
}
const result = swap(['string', 123])
let test = 123
interface GithubResp {
name: string;
count: number;
}
interface CountryResp {
name: string;
area: number;
population: number;
}
function withAPI<T>(url: string): Promise<T> {
return fetch(url).then(resp => resp.json())
}
withAPI<CountryResp>('country.resp').then(resp => {
})
定义文件 基础知识
/**
* 文件名称:myFetch.d.ts
* 如果以.d.ts后缀的文件是:声明文件
*
*
调用方式:
myFetch.get<number>('test').then(data => {
// data是number类型
})
*
*/
type HTTPMethod = 'GET' | 'POST' | 'PATCH' | 'DELETE'
// T = any默认值为any,也可以不传
declare function myFetch<T = any>(url: string, method: HTTPMethod, data?: any) : Promise<T>
declare namespace myFetch {
const get: <T = any>(url: string) => Promise<T>;
const post: <T = any>(url: string, data: any) => Promise<T>;
}
export = myFetch
网友评论