js数据类型:
7种原始类型:Boolean Null Undefined Number Bigint String Symbol
Object 类型
let isDone: boolean = false
let num: number = 10
let str: string = `
num = ${num}
isDone = ${isDone}
`
let u: undefined = undefined
let n: null = null
// any 类型数据,就像js种变量。避免使用
let notSure: any = 4
notSure = 'sdsd'
notSure = true
notSure.fun()
notSure.attr
// 数组
let arrNum: number[] = [1,2,3]
let arrStr: string[] = ['1','2','3']
// array-like object,类似数组,但是没有 push pop 等操作
function test(param1:any) {
// arguments 为ts内置的类数组
console.log(arguments[0]);
console.log(arguments.length);
}
// tuple
let user: [string, number] = ['name', 1]
接口
// 接口
interface Person {
readonly id: number // 只读属性
name: string
age?: number // 可选字段
}
let a: Person = {
id: 1,
name: 'aaaa',
// age: 1,
}
函数
// 函数
interface AddFun {
(x: number, y: number, z?:number):number
}
function fun(a:number, b:number = 0, c?:number) :number {
if (typeof c === 'number') {
return a + b + c
} else {
return a + b
}
}
fun(1)
fun(1,1)
fun(1,2,2)
let f: AddFun = fun
联合类型 类型断言
// union types, 只能访问所有类型都拥有的属性或方法
let numOrStr : number|string
numOrStr = 'abc'
numOrStr = 1
// 类型断言,不是类型转化,将变量断言为联合类型中不存在类型会出错
function getLength(input: string|number) :number {
const str = input as string
if (str.length) {
return str.length
} else {
const number = input as number
return number.toString().length
}
}
getLength(numOrStr)
// type guard
function getLength2(input: string|number) :number {
if (typeof input === 'string') {
return input.length
} else {
return input.toString().length
}
}
类
Public 默认;Private ;Protected 子类允许访问class Animal {
readonly name: string; // 在ts中类的属性在此声明,使用readonly声明为只读
constructor(name: string) {
this.name = name
}
protected run() {
return `${this.name} is running`
}
}
const snake = new Animal('aaa')
console.log(snake.run()) // 此处无法调用
class Dog extends Animal {
static categories = ['Animal']
constructor(name: string) {
super(name)
console.log(this.name)
}
bark() {
return `${this.name} is barking`
}
run() {
return `被重写:` + super.run() // 此处可以访问
}
}
const d = new Dog('ddd')
console.log(d.bark())
console.log(d.run())
console.log(Dog.categories)
接口与类
interface Radio {
switchRadio(trigger: boolean): void;
}
interface Battery {
switchBatteryStatus() : void;
}
interface RadioWithBattery extends Radio, Battery {
checkBatteryStatus(): void;
}
class Car implements Radio {
switchRadio(trigger: boolean): void {
}
}
class Cellphone implements RadioWithBattery {
checkBatteryStatus(): void {
}
switchRadio(trigger: boolean): void {
}
switchBatteryStatus(): void {
}
}
枚举类
对于常量值,在 enum 前加上 const,开始内联,将所有使用枚举值的地方改为常量,提升性能
enum Direction {
Up, // 0
Down = 10, // 10
Left, // 11
Right, // 12
}
console.log(Direction.Up) // 0
console.log(Direction[0]) // Up
enum Direction {
Up = 'UP',
Down = 'DOWN',
Left = 'LEFT',
Right = 'RIGHT',
}
if ('UP' === Direction.Up) {
console.log('go up')
}
泛型
function echo<T>(arg: T): T {
return arg
}
let str = 'string'
let res = echo(str)
let resNum = echo(123)
function swap<T, U>(tuple: [T, U]): [U, T] {
return [tuple[1], tuple[0]]
}
let t: [number, string] = [1, 'a']
let resTuple: [string, number] = swap(t)
// 泛型约束
interface IWithLength {
length: number
}
function getLenth<T extends IWithLength>(arg: T): number {
return arg.length
}
getLenth('123')
getLenth([1,2,3])
getLenth({'1':1, '2':2})
泛型与类、接口
class Queue<T> {
private data: T[] = [];
push(item: T) {
return this.data.push(item)
}
pop(): T|undefined {
return this.data.shift()
}
}
const q = new Queue<number>()
q.push(1)
q.push(2)
// q.push('12') // error
q.pop()
q.pop()
interface KeyPair<T, U> {
key: T,
value: U,
}
let kp1: KeyPair<string, number> = {key: '1', value: 1}
// 内置类型
let p1: Array<number> = [1,2,3]
类型别名,字面量 和 交叉类型
// 类型别名
type PluseType = (x: number, y: number) => number
let sumFun: PluseType
type int = number
type StrOrNum = string | number
// 类型为原始类型,
const str: 'name' = 'name'
const num: 1 = 1
// 字面量与类型别名组合
type Directions = 'Up'|'Down'|'Left'|'Right'
let toWhere: Directions = 'Left'
// 交叉类型
interface IName {
name: string
}
type IPerson = IName & {age: number}
let person: IPerson = {name: '123', age: 123}
声明文件
TS调用js库如jQuery,需要使用 declare var
声明变量已存在,然后直接使用。通常将声明语句放在一个单独的文件,如 jQuery.d.ts。可通过 npm install --save @types/jquery
安装jQuery的声明文件。
内置类型
在全局作用域存在的对象(ECMAscript,DOM等标准),
// global objects
const a: Array<number> = [1,2,3]
const data = new Date()
const reg: RegExp = /abc/
// build-in object
Math.pow(2,2)
// DOM and BOM
let body = document.body
let allLis = document.querySelectorAll('li')
document.addEventListener('click', (e)=>{
e.preventDefault()
})
// Utility Types
// Ts提供的工具类 https://www.typescriptlang.org/docs/handbook/utility-types.html
标签:typescript,return,name,number,let,const,string,入门 From: https://www.cnblogs.com/zhh567/p/17076981.html