我能检查一个字符串是否存在于接口键中吗?
interface list {
one: string
two: string
}
const myNumber = "one"
我怎样检查 myNumber 的值是不是接口(interface)的键(key)
我能检查一个字符串是否存在于接口键中吗?
interface list {
one: string
two: string
}
const myNumber = "one"
我怎样检查 myNumber 的值是不是接口(interface)的键(key)
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)
)
);
Typescript的类型不是一个值。
因此,无法操作Javascript。
然而,在这个例子中,可以设置类型,以便myNumber是与键对应的类型。
interface list {
one: string
two: string
}
const myNumber: keyof list = "one"; // myNumber allow only "one" or "two";
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);
}