TypeScript 如何检查一个字符串是否存在于接口中的键名中?

8

我能检查一个字符串是否存在于接口键中吗?

interface list {
    one: string
    two: string
}

const myNumber = "one"

我怎样检查 myNumber 的值是不是接口(interface)的键(key)


你想要实现什么目标?如果该值在接口中或者不在接口中,你希望发生什么?当它不在接口中时,你想要触发编译时错误还是类似的操作? - CertainPerformance
1
我有一个对象字面量,除了“列表”接口的键之外,还有其他键,并希望仅使用这些键来过滤该对象。 - succeed
3个回答

3
为了实现这一点,您需要有一些东西可以让您在运行时获取接口的键。一个 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)
    )
);

可运行的链接


3

Typescript的类型不是一个值。

因此,无法操作Javascript。

然而,在这个例子中,可以设置类型,以便myNumber是与键对应的类型。

interface list {
    one: string
    two: string
}

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

0
你可以像这样使用 typeguard 函数,如果你有一个实现了此接口的对象:
interface List {
    one: string
    two: string
}

const list: List = {
    one: "some one"
    two: "some two"
}

function isListKey(value: string, list: IList): value is keyof List {
    return Object.keys(list).includes(value);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接