打字稿检查字符串是否作为接口键存在
Typescript Check If A String Exists as An Interface Key
我可以检查一个字符串是否作为接口键存在吗
interface list {
one: string
two: string
}
const myNumber = "one"
如何检查 myNumber 值是否为接口键
为此,您需要有一些东西可以让您在运行时获取接口的密钥。 interface
在运行时不存在 - 它纯粹是一个 TypeScript 构造,因此它不存在于发出的代码中。
制作一个包含键的数组,声明它 as const
这样它就不会自动获取 type-widened,然后您就可以将它变成 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)
)
);
Typescript 的类型不是一个值。
因此Javascript的操作是不可能的。
但是在例子中,可以设置type,让myNumber为key对应的type
interface list {
one: string
two: string
}
const myNumber: keyof list = "one"; // myNumber allow only "one" or "two";
我可以检查一个字符串是否作为接口键存在吗
interface list {
one: string
two: string
}
const myNumber = "one"
如何检查 myNumber 值是否为接口键
为此,您需要有一些东西可以让您在运行时获取接口的密钥。 interface
在运行时不存在 - 它纯粹是一个 TypeScript 构造,因此它不存在于发出的代码中。
制作一个包含键的数组,声明它 as const
这样它就不会自动获取 type-widened,然后您就可以将它变成 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)
)
);
Typescript 的类型不是一个值。
因此Javascript的操作是不可能的。
但是在例子中,可以设置type,让myNumber为key对应的type
interface list {
one: string
two: string
}
const myNumber: keyof list = "one"; // myNumber allow only "one" or "two";