首页 > 解决方案 > 具有映射类型的代理

问题描述

我浏览了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;
  }

我无法控制循环内的类型,并且所有内容都必须是那里的任何类型。假设我的实现完全正确,如何应对?

标签: typescripttype-aliasmapped-types

解决方案


实施似乎没问题。在创建对象时会丢失一些安全性,但您不会全部丢失。你仍然得到的打字量实际上可能会让你大吃一惊

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;
}

推荐阅读