【问题标题】:Is there a way to pass the data of one interface property as "this" to another property?有没有办法将一个接口属性的数据作为“this”传递给另一个属性?
【发布时间】:2019-01-16 15:20:55
【问题描述】:

我正试图围绕接口中的泛型类型,并将一个接口属性的数据传递给另一个。

举个例子可能更容易理解:

interface IExample {
    model: () => Record<string, any>
    evaluator: Record<string, () => boolean>
}

用例是这样的:

const example: IExample = {
    model: () => {
        // The content can be changed by the user
        return {
            k1: true,
            k2: 'some content',
            k3: [1, 2, 3]
        }
    },
    evaluator: {
        testEvaluator: function () {
            /**
             * This is where I would like to have an autocompletion
             * So internally example.model() is called and
             * the return value is passed as `this`-argument
             */
            return this.k1 === true
        }
    }
}

如代码注释中所述,我想提供自动完成功能 当用户为评估者编写代码时向用户展示

到目前为止,我尝试过的大致是这样的:

interface IExample<Model extends Record<string, any> = Record<string, any>> {
    model: () => Data,
    evaluator: <Record<string, (this: Data) => boolean>
}

这甚至可能吗?如果是这样:我真的很感激任何提示。

【问题讨论】:

    标签: typescript generics interface


    【解决方案1】:

    您的类型非常接近,问题是打字稿不会对变量执行任何推断。如果您在变量类型注释中设置类型,那么这就是最终类型。

    要获得您想要的推理行为,您需要使用一个函数。函数可以有额外的类型参数,编译器将根据实际参数类型推断:

    interface IExample<Model extends Record<string, any>> {
      model: () => Model,
      evaluator: Record<string, (this: Model) => boolean>
    }
    
    function createExample<T>(o: IExample<T>) {
      return o;
    }
    
    const example = createExample({
      model: () => ({
        k1: true,
        k2: 'some content',
        k3: [1, 2, 3]
      }),
      evaluator: {
        testEvaluator: function () {
          // this is  { k1: boolean; k2: string; k3: number[]; }
    
          return this.k1 === true
        }
      }
    });
    

    【讨论】:

    • 这太棒了。非常感谢,特别是解释。像魅力一样工作
    猜你喜欢
    • 1970-01-01
    • 2019-07-30
    • 1970-01-01
    • 2022-08-20
    • 1970-01-01
    • 2013-08-14
    • 1970-01-01
    • 1970-01-01
    • 2017-01-29
    相关资源
    最近更新 更多