类型别名 主要用于重复使用
type ID = string | number // 可重复使用
type obj = {
x: number,
y: number
}
function getID(id:ID){
console.log(id)
}
function setId(id:ID){
console.log(id)
}
function getObj(pt:obj){
console.log(pt.x)
}
setId('33')
getID(55)
getObj({
x: 10,
y: 10
})
接口类型
interface Beer {
name: string
}
function add (op:Beer) {
}
add({name:'333'})
接口与别名的不同 扩展
- 都可以扩展其类型 写法有差异
- 接口扩展比 别名扩展多一种方式
// 接口扩展
interface Beer {
name: string
}
interface Join extends Beer {
age: number
}
const beer: Join ={
name:'123',
age: 12
}
console.log(beer.name)
console.log(beer.age)
// 类型别名扩展
type Juli ={
name: string
}
type july = Juli & {
age: number
}
const total: july = {
name:'123',
age: 12
}
console.log(total.name)
console.log(total.age)
// 接口向现有类型添加字段
interface A {
name: string
}
interface A {
age: number
}
const b : A = {
name:'123',
age: 12
}
console.log(b.age, b.name)
类型断言
const myCanvas = document.getElementById('mainCanvas') as HTMLCanvasElement
const myCanvas2 = <HTMLCanvasElement>document.getElementById('mainCanvas')
const x = ('hallo' as unknown) as string
文字类型
function position (a: string, alignment?: 'left' | 'center' | 'right' ){
console.log(a, alignment)
}
position('11',"left")
position('22',"center")
function position (a: string, alignment?: 'left' | 'center' | 'right' ){
console.log(a, alignment)
}
const obj = {
a:'11',
b:'left'
} as const
position(obj.a,obj.b)
// 一定要加类型断言 as const 字符串类型不能推断成具体的值
let x: number = 1
let y : null = null
function add (a: number | null ){
a!.toFixed(2)
}
add(x)
add(y)
// !. 断言a 的值不是null 或者 undefined 只有 null| undefined 才能用