【问题标题】:Typescript Check If A String Exists as An Interface Key打字稿检查字符串是否作为接口键存在
【发布时间】:2020-10-27 23:49:16
【问题描述】:

我可以检查一个字符串是否作为接口键存在

interface list {
    one: string
    two: string
}

const myNumber = "one"

如何检查 myNumber 值是否为接口键

【问题讨论】:

  • 你想完成什么?如果值在接口中,或者不在接口中,您希望发生什么?当它不在界面中时,您是否想引发编译时错误,或者类似的东西?
  • 我有一个对象字面量,除了 'list' 接口的键之外还有键,并希望仅在 'list' 接口中使用这些键过滤该对象

标签: typescript interface


【解决方案1】:

Typescript 的类型不是值。

因此,无法运行Javascript。

但是,在示例中,可以设置类型,使 myNumber 为键对应的类型。

interface list {
    one: string
    two: string
}

const myNumber: keyof list = "one"; // myNumber allow only "one" or "two";

【讨论】:

    【解决方案2】:

    为此,您需要有一些东西可以让您在运行时获取接口的密钥。 interface 在运行时不存在 - 它纯粹是一个 TypeScript 构造,因此它不存在于发出的代码中。

    创建一个包含键的数组,将其声明为as const,这样它就不会自动扩展类型,然后您就可以将其转换为List 类型。然后,您将拥有一个类型和一个运行时数组,您可以使用 .includes 检查:

    const listKeys = ['one', 'two'] as const;
    type List = Record<typeof listKeys[number], string>;
    
    // ...
    
    const obj = {
        one: 'one',
        two: 'two',
        three: 'three'
    };
    // Transformation to string[] needed because of an odd design decision:
    // https://github.com/Microsoft/TypeScript/issues/26255
    const newObj = Object.fromEntries(
        Object.entries(obj).filter(
            ([key]) => (listKeys as unknown as string[]).includes(key)
        )
    );
    

    Playground link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-03
      • 2020-04-30
      • 2014-06-19
      相关资源
      最近更新 更多