1.联合类型
联合类型,即我们可以指定一个变量的值是多个类型
const phone:number | string = '102-34313'
function transformData(data:number | boolean):boolean {
return !!data
}
console.log(transformData(1))
2. 交叉类型
交叉类型,相当于多继承,即可以合并两个接口的所有类型约束
interface A{
name: string,
age: number
}
interface B {
address: string
}
function print(person: A & B):void {
console.log(person)
}
print({name:'jjs',age:11,address:"sdw"})
3. 类型断言
类型断言,可以指定数据的具体类型,但是也仅仅是让ts编译器知道该类型 但是并不会发生修改,也可以将let类型断言为const类型
interface C {
run:string
}
interface D {
build:string
}
function print2(type:C | D):void {
console.log((type as C).run)
}
let test = 1 as const
// test = 3 这样就会出错
4. ts 对于class的一些操作
1. class 的基本用法 继承 和 类型约束 2. class 的修饰符 readonly private protected public 3. super 原理 4. 静态方法 5. get set 6. 抽象类
抽象类不可以被实例化,可有有抽象方法,继承他的类必要实现
静态方法不可以调用非静态成员,非静态方法可以调用静态方法和属性
abstract class Aclass {
init() {
console.log("init")
}
abstract fn(name:string):number
}
class Bclass extends Aclass {
constructor() {
super();
this.init()
}
fn(name: string): number {
return 0;
}
}
class Person {
static id:number = 0
private _value:string | number
constructor(_value:string | number) {
this._value = _value
}
private a: string = 'aaa'
get value() {
return this._value + this.a
}
set value(newValue:string | number) {
this._value = newValue
}
}
const person = new Person(123)
person.value = 345
console.log(person.value,Person.id++)
继承,修饰符,super的用法
interface Options {
el: string | HTMLElement
}
interface ClsInterface {
option: Options,
init(): void
}
interface Vnode {
tag:string,
text?: string,
props?: {
id?:number | string,
key?:number | string | object
},
children?: Vnode[]
}
class Dom {
constructor() {
}
private createElement(el:string):HTMLElement {
return document.createElement(el)
}
protected setText(el: Element, text: string | null) {
el.textContent = text;
}
protected render(createElement: Vnode): HTMLElement {
const el = this.createElement(createElement.tag)
if (createElement.children && Array.isArray(createElement.children)) {
createElement.children.forEach(item => {
const child = this.render(item)
this.setText(child, item.text ?? null)
el.appendChild(child)
})
} else {
this.setText(el, createElement.text ?? null)
}
return el;
}
}
class VNode extends Dom implements ClsInterface {
option:Options
constructor(option:Options) {
super()
this.option = option
this.init()
}
init() {
let app = typeof this.option.el == 'string' ? document.querySelector(this.option.el) : this.option.el;
let data: Vnode = {
tag: "div",
props: {
id: 1,
key: 1
},
children: [
{
tag: "div",
text: "子集1",
},
{
tag: "div",
text: "子集2"
}
]
}
app?.appendChild(this.render(data))
}
}