🚧 常用TypeScript高级类型体操 🚧
interface ObjectMap { button: HTMLButtonElement; input: HTMLInputElement; textarea: HTMLTextAreaElement;}
function handleEvent(event: keyof ObjectMap) { console.log(event); // button, input, textarea}
handleEvent('button'); // button
handleEvent('img'); // Error: 这里会发生类型错误interface ObjectMap { button: HTMLButtonElement; input: HTMLInputElement; textarea: HTMLTextAreaElement;}
function pushEvent<T extends keyof ObjectMap>(event: T, element: ObjectMap[T]) {}
// 传入button类型,element会被推断为HTMLButtonElement类型pushEvent('button', new HTMLButtonElement());