首页 > 解决方案 > 打字稿检查字符串是否作为接口键存在

问题描述

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

interface list {
    one: string
    two: string
}

const myNumber = "one"

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

标签: typescriptinterface

解决方案


为此,您需要有一些东西可以让您在运行时获取接口的密钥。Aninterface在运行时不存在 - 它纯粹是一个 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)
    )
);

游乐场链接


推荐阅读