gpt4 book ai didi

typescript - 如何将正确的类型设置为定义的对象键之一?

转载 作者:搜寻专家 更新时间:2023-10-30 21:33:33 24 4
gpt4 key购买 nike

我构建了这个片段来演示我的问题:

const typeEnum = {
a: 1,
b: 2,
c: 3,
d: 4,
e: 5
};


const isCD = (...types: any[]) => {
return types.some(t => {
return t == typeEnum.c || t == typeEnum.d;
});
};

console.log(
isCD(
typeEnum.a,
typeEnum.b,
typeEnum.d,
6
)
);

所以我想要的是将 any[] 替换为正确的类型,但我不知道如何设置可接受的值是来自 typeEnum 的值键,因此没有人会将 6 作为参数传递,因为它不是可接受的参数。

TypeScript Playground link

提前致谢。


我最后的工作片段以这种方式结束:

const typeEnum = {
a: 1,
b: 2,
c: 3,
d: 4,
e: 5
} as const;

type typeEnumValues = typeof typeEnum [keyof typeof typeEnum];

const isCD = (...types: typeEnumValues[]) => {
return types.some(t => {
return t == typeEnum.c || t == typeEnum.d;
});
};

console.log(
isCD(
typeEnum.a,
typeEnum.b,
typeEnum.d,
6
)
);

TypeScript Playground link

最佳答案

对于 TS3.4+,您可以使用 const assertion告诉编译器 typeEnum 的类型应该被推断为尽可能窄... 3 的属性值将被推断为数字文字 3 而不是 number:

const typeEnum = {
a: 1,
b: 2,
c: 3,
d: 4,
e: 5
} as const;
// inferred as type { readonly a: 1; readonly b: 2; readonly c: 3;
// readonly d: 4; readonly e: 5; }

如果您还没有更新到 TS3.4,您可以使用辅助函数获得类似的行为:

const litNumVals =
<N extends number, T extends { [k: string]: N }>(t: T) => t;

const typeEnum = litNumVals({
a: 1,
b: 2,
c: 3,
d: 4,
e: 5
});
// inferred as type { a: 1; b: 2; c: 3; d: 4; e: 5; }

根据 那个 值,您可以使用类型函数来约束 isCD 参数:

type ValueOf<T> = T[keyof T]

type TypeEnumValues = ValueOf<typeof typeEnum>;
// 1 | 2 | 3 | 4 | 5

const isCD = (...types: Array<TypeEnumValues>) => {
return types.some(t => {
return t == typeEnum.c || t == typeEnum.d;
});
};

console.log(
isCD(
typeEnum.a, // okay
typeEnum.b, // okay
typeEnum.d, // okay
6 // error
)
);

好的,希望对你有帮助。祝你好运!

关于typescript - 如何将正确的类型设置为定义的对象键之一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55621529/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com