【发布时间】:2019-10-31 04:33:31
【问题描述】:
我正在尝试导出具有有效类型的对象并基于它创建类型。它按预期工作。这里的问题是 Option 接口不接受对象键作为键名,即使它们是字符串。
export const SortValues = {
NEWER: 'NEWER',
OLDER: 'OLDER',
NAME_ASC: 'NAME_ASC',
NAME_DESC: 'NAME_DESC',
}
interface Option<T = string> {
key: T;
value: string;
}
type SortValuesType = keyof typeof SortValues;
// type SortValuesType = 'NEWER' | 'OLDER' | 'NAME_ASC' | 'NAME_DESC'; // This also doesn't work.
export const options: Array<Option<SortValuesType>> = [
{ key: SortValues.NEWER, value: 'Mais novos' },
{ key: SortValues.OLDER, value: 'Mais antigos' },
{ key: SortValues.NAME_ASC, value: 'A - Z' },
{ key: SortValues.NAME_DESC, value: 'Z - A' },
];
我在 options 的 key prop 上收到错误 "Type 'string' is not assignable to type '"NEWER" | "OLDER" | "NAME_ASC" | "NAME_DESC"'."。
此外,如果我将 SortValues 定义为枚举,它也可以工作,但是它会给我带来一些其他问题,所以我需要将它导出为对象。
这是一个sn-p https://codesandbox.io/s/fqide
【问题讨论】:
标签: typescript types typescript-typings