【发布时间】:2021-07-19 22:11:06
【问题描述】:
以下函数的推断返回类型为{[k: string]: number}:
export const dateParts = (
date: Date,
timeZone?: string
) => {
const options = {
day: "numeric",
month: "numeric",
timeZone,
year: "numeric",
} as const;
const formatter = new Intl.DateTimeFormat("en", options);
const parts = formatter.formatToParts(date);
return Object.fromEntries(
parts
.filter(({ type }) => ["year", "month", "day"].includes(type))
.map(({ type, value }) => [type, Number(value)])
);
};
但对于返回对象的键,唯一可能的选项是 year、month 和 day。
有没有办法将返回对象的键限制为只有那些?
我尝试将返回类型显式添加为{'year': number, 'month': number, 'day': number} 或Record<'year' | 'month' | 'day', number>:
export const dateParts = (
date: Date,
timeZone?: string
): { year: number; month: number; day: number } => {
但它与 Object.fromEntries 返回的内容冲突:
Type '{ [k: string]: number; }' is missing the following properties from type '{ year: number; month: number; day: number; }': 'year', 'month', 'day' ts(2739)
我无法弄清楚如何修改Object.fromEntries 的返回类型,使其匹配{'year': number, 'month': number, 'day': number} 而不是{[k: string]: number}。
【问题讨论】:
-
"它与什么 Object.fromEntries 冲突" - 您可以发布您在使用
Object.fromEntries(…) as …和首选返回类型时遇到的类型错误吗? -
@Bergi 用
as转换返回的类型可以工作......但是,我们可以让它推断出正确的类型而不是转换它吗? -
我对此表示怀疑。通用
Object内置函数在 Typescript 中的输入非常糟糕。看看stackoverflow.com/q/59996713/1048572、github.com/microsoft/TypeScript/issues/31393,尤其是github.com/microsoft/TypeScript/issues/35745
标签: javascript typescript types typescript-typings