typescript - 具有映射类型的代理
问题描述
我浏览了TS 手册并找到了映射类型。有一个代码片段可以将对象属性包装到代理中。
type Proxy<T> = {
get(): T;
set(value: T): void;
}
type Proxify<T> = {
[P in keyof T]: Proxy<T[P]>;
}
function proxify<T>(o: T): Proxify<T> {
// ... wrap proxies ...
}
let proxyProps = proxify(props);
我试图用我的实现来填补代理函数中的空白,我得到了这样的东西:
function proxify<T>(t: T): Proxify<T> {
let result = <Proxify<T>>{};
for (const k in t) {
result[k] = { //(*) from that moment I lose strong typing
get: () => t[k],
set: (value) => t[k] = value
}
}
return result;
}
我无法控制循环内的类型,并且所有内容都必须是那里的任何类型。假设我的实现完全正确,如何应对?
解决方案
实施似乎没问题。在创建对象时会丢失一些安全性,但您不会全部丢失。你仍然得到的打字量实际上可能会让你大吃一惊
function proxify<T>(t: T): Proxify<T> {
let result = <Proxify<T>>{};
for (const k in t) { // k is of type Extract<keyof T, string> so it must be a key of T
// result[k] and t[k] both work because k is a key of both T and Proxify<T> but result['random'] would be invalid
result[k] = { // get/set fields are checked, so _get would be an error
// the return of get must be T[Extract<keyof T, string>] so ()=> 0 would be an error
get: () => t[k],
// value and t[k] must be T[Extract<keyof T, string>] so t[k] = '' would also be an error
set: (value) => t[k] = value
}
}
return result;
}
推荐阅读
- mdc-components - 从按钮打开 MDCMenu
- python - 如何使用按钮指向现有 url
- c++ - 在父类中为多个孩子定义方法
- reactjs - 无法分配给“postCount”,因为它是只读属性。ts(2540) spfx
- powershell - 在 slack 上发布图像时获取“invalid_form_data”
- css - 如何用白色背景颜色但宽度较低且居中填充 div?
- css - 相关产品块图像的 Magento 2 样式背后的基本原理是什么?
- kubernetes - 使用 cadvisor 监视具有不同 gpu 驱动程序的服务器的最佳实践是什么
- git - 功能分支和远程主分支之间的 Git 差异
- azure-active-directory - 如果我的所有资源都在同一个订阅中,是否真正使用用户分配的托管标识?