javascript - 在这种情况下,将对象引用传递到 Date.toLocaleString() 中,TypeScript linter 到底要求什么?

标签 javascript typescript

我已经遇到这个问题有一段时间了。代码确实运行没有问题,但我觉得我应该弄清楚 TypeScript 的 linter 关心什么。 这是我能得到的最简单的重现,LocaleConfig 是红色突出显示的内容。

let Today = new Date();
let LocaleConfig = {dateStyle: "full"};
console.log(Today.toLocaleString([], LocaleConfig));

我注意到,根据目标版本,linter 会出现不同的错误。这是默认 ES3 的结果。

 No overload matches this call.
   Overload 1 of 3, '(locales?: LocalesArgument, options?: DateTimeFormatOptions | undefined): string', gave the following error.
     Argument of type '{ dateStyle: string; }' is not assignable to parameter of type 'DateTimeFormatOptions'.
       Types of property 'dateStyle' are incompatible.
         Type 'string' is not assignable to type '\"full\" | \"long\" | \"medium\" | \"short\" | undefined'.
   Overload 2 of 3, '(locales?: string | string[] | undefined, options?: DateTimeFormatOptions | undefined): string', gave the following error.
     Argument of type '{ dateStyle: string; }' is not assignable to parameter of type 'DateTimeFormatOptions'.
{source: ts, code: 2769, severity: 8}

这是来自 ES6 的。错误出现在同一个单词上。

Type '{ dateStyle: string; }' has no properties in common with type 'DateTimeFormatOptions'.
{source: ts, code: 2559, severity: 8}

最佳答案

这里有 2 个单独的问题。

类型 '{ dateStyle: string; }' 与“DateTimeFormatOptions”类型没有共同的属性。

target设置为ES2020之前的任何内容时,即属性被添加到规范中时,就会发生这种情况。查找draft这里。 ES6 == ES2015 因此当它被定位时它会丢失。

类型“string”不可分配给类型““full”| “长”| “中”| “短”|未定义'。

这是因为字符串文字的工作方式。如果没有类型断言,则只能确定 dateStyle 的类型为 string。它可以随时更改为不属于有效文字联合体的内容,因此无法可靠地分配给它。

这可以通过多种方式解决,但本质上您需要告诉 TS dateStyle 属性属于某种符合预期类型的​​文字类型或文字类型的联合。

我们知道完整的预期类型,因此我们可以使用它:
let LocaleConfig: Intl.DateTimeFormatOptions = { dateStyle: 'full' };
我们可以通过多种方式将断言输入为文字:
let LocaleConfig = { dateStyle: 'full' as 'full' };
let LocaleConfig = { dateStyle: 'full' as 'full' | 'long' };
let LocaleConfig = { dateStyle: 'full' as Intl.DateTimeFormatOptions['dateStyle'] };
我们可以通过多种方式将assert键入为const:
let LocaleConfig = { dateStyle: 'full' as const };
let LocaleConfig = { dateStyle: 'full' } as const;

From TS handbook :

The as const suffix acts like const but for the type system, ensuring that all properties are assigned the literal type instead of a more general version like string or number.

还发现this围绕这个问题回答。

关于javascript - 在这种情况下,将对象引用传递到 Date.toLocaleString() 中,TypeScript linter 到底要求什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73563950/

相关文章:

javascript - 根据用户选择向 CQ5 对话框中的多字段动态添加验证

javascript - 如何将一个对象json转换为数组对象json?

typescript - 为对象的键添加前缀仅考虑重叠

reactjs -/home/Documents/node_modules/cheerio-select/lib/index.d.ts(1,15) : [0] ',' expected. TS1005 中的 TypeScript 错误

typescript - 定义和使用泛型键值列表

javascript - typescript | JavaScript | Angular 2 | @Output 与 @Input

javascript - 从两个下拉列表中选择值时如何显示 div?

javascript - document.fullScreen 歌剧

javascript - Angular 6依赖注入(inject)

typescript - 获取函数/类构造函数的参数类型