TypeScript 高级类型应用与技巧
1. 创建元素函数的优化
在创建元素时,我们可以使用如下代码:
const elem = document.createElement(tag as string) as AllElements[T];
return Object.assign(elem, props);
}
const a = createElement("a", { href: "https://fettblog.eu" }); // OK
const b = createElement("my-element"); // OK
const c = createElement("thisWillError");
// ^
// Argument of type '"thisWillError"' is not
// assignable to parameter of type '`${string}-${string}`
// | keyof HTMLElementTagNameMap'.(2345)
这里使用 AllElements 类型会带来类型断言问题,我们可以使用函数重载来解决。函数重载的定义如下:
function createElement<T extends keyof AllElements>(
tag: T,
props?: Partial<AllElements[T]>
超级会员免费看
订阅专栏 解锁全文
1091

被折叠的 条评论
为什么被折叠?



