typescript - 具有映射类型的代理

标签 typescript type-alias mapped-types

我走过TS Handbook我来到了映射类型。有一个代码片段可以将对象属性包装到代理中。

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

我试图用我的实现来填补 proxify 函数中的空白,我得到了这样的结果:

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

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

最佳答案

实现似乎没问题。创建对象时会失去一些安全性,但您不会失去所有安全性。您仍然获得的打字量实际上可能会让您感到惊讶

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

关于typescript - 具有映射类型的代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51326583/

相关文章:

typescript - 映射类型时省略只读属性

javascript - 使用 Material UI react 自动完成

css - Angular - 使用变换制作动画,但在动画完成时不应用绝对位置

swift - 约束类型别名不使用约束

Swift:类型别名和协议(protocol)中具有值的关联类型有什么区别?

Typescript:映射类型,使除所选属性之外的每个属性均为只读

条件类型的 typescript 枚举类型检查?

reactjs - 如何从继承类覆盖 React.Component 状态类型?

javascript - 如何使用 Jest 和 typescript 模拟模块变量