【问题标题】:Typescript: setting a property to be a particular type打字稿:将属性设置为特定类型
【发布时间】:2021-03-21 18:47:02
【问题描述】:

我是 Typescript 的新手,只是探索如何转换我们现有的 JS 代码。我的方法(可能有缺陷)是做最少的事情让它在 TypeScript 中工作,然后逐渐将其转换为遵循“最佳实践”。

我好像在第一道关口就掉下来了.....

我有以下 TypeScript,使用 jQuery(在 ASP.NET .NET5 应用程序中)。

interface MyInterface {
    prop1: string;
    prop2: number;
}

const something = {
    currentThing : MyInterface,

    init: (): void => {
        //
    }
};

$(something.init);

所以想法是当页面加载时,something.init 将被执行。这将设置诸如事件处理程序通过 jQuery 选择器,。所有这部分似乎都可以正常工作。

不过……

在某个时候,一个事件处理程序将触发,我将创建一个将实现MyInterface 的新对象。我需要保留它(通过将其设置为属性/字段currentThing 的值),以便以后的事件可以访问它。

但是,Typescript 不喜欢 currentActivity: MyInterface, 行,我得到了错误:

'MyInterface' 仅指一种类型,但在这里用作值。

【问题讨论】:

  • 您不能将类型分配给对象字面量内的属性。您需要为something 对象分配一个类型for,例如const something: { currentThing: MyInterface, init: () => void } = { /* ... */}。提取该接口可能也是一个好主意。

标签: javascript typescript


【解决方案1】:

一个对象遵循键值结构,Typescript将当前对象定义理解为

const something = {
    //    key         value
    currentThing : MyInterface,    
};

由于MyInterface 不是有效值,它会抛出上述错误。

在这种情况下,您应该为 something 对象定义类型,键入其属性,如下所示:

interface MyInterface {
    prop1: string;
    prop2: number;
}

interface SomethingInterface {
    currentThing : MyInterface;
    init: () => void
}

const currentThing = { prop1: 'aStringValue', prop2: 12345 };
const something: SomethingInterface = {
    currentThing,
    init: (): void => {
        //
    }
};

$(something.init);

【讨论】:

  • 我尝试了上述方法(可行),但进行了以下调整。我想听听我的适应是否被视为一种好的做法......我从const currentThing = { prop1: 'aStringValue', prop2: 12345 }; 更改为const currentThing: MyInterface = null;,因为我不热衷于创建一个虚拟对象。我也不确定这是否应该是 const... 在 init 函数中,我可以使用 something.currentThing = { prop1: "abc", prop2: 12345 }; 设置它并稍后检索它。
  • 你考虑过使用class吗?例如,您可以将init() 替换为constructor(),然后调用$(new Something(currentThing))
【解决方案2】:

我建议您使用新界面like 输入您的something 对象:

interface MyInterface {
    prop1: string;
    prop2: number;
}

interface Something {
  currentThing: MyInterface;
  init: () => void;
}

const something: Something = {
    currentThing: {
      prop1: 'foo',
      prop2: 5,
    },

    init: (): void => {
        //
    },
};

console.log(something.init);

【讨论】:

    【解决方案3】:

    正如其他人所说,您不能对对象文字中的字段使用类型。如有必要,我会改用一个类使其更具可读性,并使用该类的实例导出一个 const。

    例子:

    interface MyInterface {
        prop1: string;
        prop2: number;
    }
    
    class Something implements MyInterface {
    
        public Something(public prop1: string, public prop2: number) {
        }
    
        init(): void {
        }
    }
    
    export const something = new Something('value1', 10);
    
    $(something.init);
    

    【讨论】:

      猜你喜欢
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 2018-01-18
      • 2018-03-27
      • 2019-03-12
      • 2021-12-30
      • 2022-01-17
      • 1970-01-01
      相关资源
      最近更新 更多