为什么我收到错误“对象文字可能只指定已知属性"? [英] Why am I getting an error "Object literal may only specify known properties"?

查看:63
本文介绍了为什么我收到错误“对象文字可能只指定已知属性"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚从 TypeScript 1.5 升级到最新版本,但在我的代码中看到一个错误:

I just upgraded from TypeScript 1.5 to the latest and I'm seeing an error in my code:

interface Options {
   /* ... others ... */
   callbackOnLocationHash?: boolean;
}

function f(opts: Options) { /* ... */ }

//  Error: Object literal may only specify known properties,
//     and 'callbackOnLoactionHash'does not exist in type 'Options'.
f( { callbackOnLoactionHash: false });

代码对我来说很好.怎么了?

Code looks fine to me. What's wrong?

(替代宇宙版本:我认出了错别字,我确实是故意写的.我应该怎么做才能消除错误?)

(Alternative universe version: I recognize the typo, and I really did mean to write that. What should I do to remove the error?)

推荐答案

从 TypeScript 1.6 开始,对象字面量中的属性如果在它们被分配的类型中没有相应的属性,则会被标记为错误.

As of TypeScript 1.6, properties in object literals that do not have a corresponding property in the type they're being assigned to are flagged as errors.

通常此错误意味着您的代码或定义文件中存在错误(通常是拼写错误).在这种情况下,正确的修复方法是修复错字.在问题中,属性 callbackOnLoactionHash 不正确,应该是 callbackOnLocationHash(注意Location"的拼写错误).

Usually this error means you have a bug (typically a typo) in your code, or in the definition file. The right fix in this case would be to fix the typo. In the question, the property callbackOnLoactionHash is incorrect and should have been callbackOnLocationHash (note the mis-spelling of "Location").

此更改还需要对定义文件进行一些更新,因此您应该为您正在使用的任何库获取最新版本的 .d.ts.

This change also required some updates in definition files, so you should get the latest version of the .d.ts for any libraries you're using.

示例:

interface TextOptions {
    alignment?: string;
    color?: string;
    padding?: number;
}
function drawText(opts: TextOptions) { ... }
drawText({ align: 'center' }); // Error, no property 'align' in 'TextOptions'

但我是想这样做

在某些情况下,您可能打算在对象中添加额外的属性.根据您的操作,有几个适当的修复

But I meant to do that

There are a few cases where you may have intended to have extra properties in your object. Depending on what you're doing, there are several appropriate fixes

有时您想确保一些东西存在并且类型正确,但无论出于何种原因打算拥有额外的属性.类型断言(vv as T)不检查额外的属性,因此您可以使用它们代替类型注释:

Sometimes you want to make sure a few things are present and of the correct type, but intend to have extra properties for whatever reason. Type assertions (<T>v or v as T) do not check for extra properties, so you can use them in place of a type annotation:

interface Options {
    x?: string;
    y?: number;
}

// Error, no property 'z' in 'Options'
let q1: Options = { x: 'foo', y: 32, z: 100 };
// OK
let q2 = { x: 'foo', y: 32, z: 100 } as Options;
// Still an error (good):
let q3 = { x: 100, y: 32, z: 100 } as Options;

这些属性,也许还有更多

某些 API 接受一个对象并动态迭代其键,但具有需要为特定类型的特殊"键.向类型添加字符串索引器将禁用额外的属性检查

These properties and maybe more

Some APIs take an object and dynamically iterate over its keys, but have 'special' keys that need to be of a certain type. Adding a string indexer to the type will disable extra property checking

之前

interface Model {
  name: string;
}
function createModel(x: Model) { ... }

// Error
createModel({name: 'hello', length: 100});

之后

interface Model {
  name: string;
  [others: string]: any;
}
function createModel(x: Model) { ... }

// OK
createModel({name: 'hello', length: 100});

这是一只狗、一只猫还是一匹马,还不确定

interface Animal { move; }
interface Dog extends Animal { woof; }
interface Cat extends Animal { meow; }
interface Horse extends Animal { neigh; }

let x: Animal;
if(...) {
  x = { move: 'doggy paddle', woof: 'bark' };
} else if(...) {
  x = { move: 'catwalk', meow: 'mrar' };
} else {
  x = { move: 'gallop', neigh: 'wilbur' };
}

这里想到了两个很好的解决方案

Two good solutions come to mind here

x

// Removes all errors
let x: Dog|Cat|Horse;

类型断言每一件事

// For each initialization
  x = { move: 'doggy paddle', woof: 'bark' } as Dog;

这种类型有时开有时不

使用交集类型的数据模型"问题的干净解决方案:

This type is sometimes open and sometimes not

A clean solution to the "data model" problem using intersection types:

interface DataModelOptions {
  name?: string;
  id?: number;
}
interface UserProperties {
  [key: string]: any;
}
function createDataModel(model: DataModelOptions & UserProperties) {
 /* ... */
}
// findDataModel can only look up by name or id
function findDataModel(model: DataModelOptions) {
 /* ... */
}
// OK
createDataModel({name: 'my model', favoriteAnimal: 'cat' });
// Error, 'ID' is not correct (should be 'id')
findDataModel({ ID: 32 });

另见 https://github.com/Microsoft/TypeScript/issues/3755

这篇关于为什么我收到错误“对象文字可能只指定已知属性"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆