导航
type Person = {
name: string
age: number
}
let user = {
name: 'Lance',
age: 18,
id: 1,
email: '[email protected]'
}
let p: Person
p = user
let user = {
name: 'Lance',
age: 18,
id: 1,
email: '[email protected]'
}
type User = typeof user
let fn1 = (a: number) => {
console.log(a);
}
let fn2 = (b: number, s: string) => {
console.log(b, s);
}
fn2 = fn1 // OK
fn1 = fn2 // 报错
interface MyEvent {
target: string
}
interface MyMouseEvent extends MyEvent {
x: number
y: number
}
let listener = (e: MyEvent) => console.log(e.target);
let mouseListener = (e: MyMouseEvent) => console.log(e.x, e.y);
mouseListener = listener
listener = mouseListener
interface MyEvent {
target: number
}
interface MyMouseEvent extends MyEvent {
x: number
y: number
}
function listenEvent(eventType: string, fn: (e: MyEvent) => void) {
/* ... */
}
// 我们希望这样用
listenEvent('click', (e: MyMouseEvent) => console.log(e.x + ',' + e.y))
// 但只能这样用
listenEvent('click', (e: MyEvent) => {
console.log((e as MyMouseEvent).x + ',' + (e as MyMouseEvent).y);
})
// 还可以这样用
listenEvent('click', ((e: MyMouseEvent) =>
console.log(e.x + ',' + e.y)) as (e: MyEvent) => void);
// 这个就太离谱了
listenEvent('click', (e: number) => console.log(e))
let a = () => {
return { name: 'Lance' }
}
let b = () => {
return { name: 'La', age: 23 }
}
b = a // 报错
a = b // OK
type JSONValue =
| string
| number
| null
| boolean
| JSONValue[]
| { [k: string]: JSONValue }
// 最后一个无线递归