【问题标题】:Interface function with some properties (TypeScript)?具有某些属性的接口函数(TypeScript)?
【发布时间】:2021-09-26 06:41:27
【问题描述】:

如何使用下面的界面?

interface Something {
 (n: number): void,
 description: string
}

我试着写下。

var sth: Something = {
    description: "Description"
}

sth = (n: number) => {
    console.log("Something");
}

var sth: Something = {
    (n: number) => {
        console.log("Something");
    },
    description: "Description"
}

但他们都给出了错误。

【问题讨论】:

    标签: javascript typescript function interface properties


    【解决方案1】:

    您不能直接创建既是函数又具有其他属性的对象。您必须分两步完成,首先创建一个函数,然后为其分配另一个道具,然后将结果分配给您界面的变量:

    interface Something {
      (n: number): void;
      description: string;
    }
    
    function fn(n: number) {}
    
    fn.description = 'foo';
    
    const h: Something = fn;
    

    【讨论】:

      【解决方案2】:

      您可以通过以下几种方式之一来实现。每个都适合带有属性的函数,但都是可行的,具体取决于用例:

      创建函数然后添加属性

      没有用于创建函数带有属性的语法。您必须分别进行:

      var sth: Something = ((n: number) => {
          console.log(n + 2);
      }) as Something;
      sth.description = "Description";
      

      Playground Link

      这里需要as Something断言,告诉编译器把函数当作Something处理,否则不能添加description

      Object.assign()

      这允许一次声明所有内容:

      var sth: Something = Object.assign(
        (n: number) => {
          console.log(n + 2);
        },
        { description: "Description"}
      );
      

      Playground Link

      Object.assign 被键入以返回 any,因此类型声明 sth: Something 确保它在之后被视为正确的对象。

      Object.defineProperty()

      创建对象的另一种方法添加属性。它允许对属性进行更多控制,例如在需要时使其不可写。

      var sth: Something = Object.defineProperty(
        (n: number) => {
          console.log(n + 2);
        },
        "description",
        { value: "Description"}
      ) as Something;
      

      Playground Link

      as Something 断言是必需的,因为 Object.defineProperty() 被键入以返回与第一个参数相同的值。所以它返回(n: number) => void

      Object.defineProperties()

      Object.defineProperty() 非常相似,但允许一次配置多个属性。

      var sth: Something = Object.defineProperties(
        (n: number) => {
          console.log(n + 2);
        },
        { 
          description: { value: "Description" }
        }
      ) as Something;
      

      Playground Link

      【讨论】:

        猜你喜欢
        • 2015-12-20
        • 2019-04-03
        • 2016-11-10
        • 1970-01-01
        • 1970-01-01
        • 2020-10-30
        • 1970-01-01
        • 1970-01-01
        • 2019-04-25
        相关资源
        最近更新 更多