无法将对象分配给文字类型

时间:2020-04-21 10:02:26

标签: typescript

{
  match: /^[\d]{2}\/[\d]{2}\/[\d]{4}$/,
  style: 67,
  fmt: function(d) {
    return Math.round(25569 + (Date.parse(d.substring(4, 8) + "-" + d.substring(2, 4) + "-" + d.substring(0, 2)) / (86400 * 1000)));
  }
} //Date dd/mm/yyyy

您可以看到我传递了完全相同的对象,但是如果我先定义它,则由于某种原因它将不起作用。

2 个答案:

答案 0 :(得分:1)

您已将string literal type用于foo属性:

foo: 'bar';

字符串文字类型允许您指定字符串必须具有的确切值

这意味着foo只能保存 'bar'个值(不能保存任何string)。

options的类型被解析为{ foo: string },因为foo是可变的。如果要强制打字稿推断文字类型,可以使用as const assertion

const options = { foo: 'bar' } as const; // type is { readonly foo: "bar"; }
example(options); // no error now

另一个选择是明确指定类型:

const options: IOptions = { foo: 'bar' };

如果您想允许foo接受任何string,请将定义更改为:

interface IOptions {
  foo: string;
}

答案 1 :(得分:0)

您需要定义选项的类型。因为仅通过定义const并不能保证您定义的变量将继续具有相同的签名,所以您可以在任何时间点添加或删除键,因为未明确定义任何类型的键都会引发错误。

interface IOptions {
    foo: 'bar';
}

const example = (opts: IOptions) => console.log(opts);

const options: IOptions = { foo: 'bar' }; // define type here
const options2 = { foo: 'bar' };

example(options); 
example(options2 as IOptions) // If you are sure that options 2 is correct type
example({ foo: 'bar' });