typescript 为什么我收到错误“对象文字可能只指定已知属性”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31816061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why am I getting an error "Object literal may only specify known properties"?
提问by Ryan Cavanaugh
I just upgraded from TypeScript 1.5 to the latest and I'm seeing an error in my code:
我刚刚从 TypeScript 1.5 升级到最新版本,但在我的代码中看到一个错误:
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?)
(替代宇宙版本:我认出了错别字,我真的是故意写的。我应该怎么做才能消除错误?)
回答by Ryan Cavanaugh
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.
从 TypeScript 1.6 开始,对象字面量中的属性在它们被分配的类型中没有对应的属性会被标记为错误。
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").
通常此错误意味着您的代码或定义文件中存在错误(通常是拼写错误)。在这种情况下,正确的修复方法是修复错字。在问题中,该属性callbackOnLoactionHash
是不正确的,应该是callbackOnLocationHash
(注意“Location”的拼写错误)。
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.
此更改还需要对定义文件进行一些更新,因此您应该为您正在使用的任何库获取最新版本的 .d.ts。
Example:
例子:
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
在某些情况下,您可能打算在对象中添加额外的属性。根据您在做什么,有几个适当的修复
Type-checking only some properties
仅对某些属性进行类型检查
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:
有时你想确保一些东西存在并且类型正确,但无论出于何种原因打算拥有额外的属性。类型断言 (<T>v
或v as T
) 不检查额外的属性,因此您可以使用它们代替类型注释:
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;
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
一些 API 接受一个对象并动态迭代它的键,但具有需要是某种类型的“特殊”键。向类型添加字符串索引器将禁用额外的属性检查
Before
前
interface Model {
name: string;
}
function createModel(x: Model) { ... }
// Error
createModel({name: 'hello', length: 100});
After
后
interface Model {
name: string;
[others: string]: any;
}
function createModel(x: Model) { ... }
// OK
createModel({name: 'hello', length: 100});
This is a dog or a cat or a horse, not sure yet
这是一只狗或一只猫或一匹马,还不确定
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
这里想到了两个很好的解决方案
Specify a closed set for x
指定一个闭集 x
// Removes all errors
let x: Dog|Cat|Horse;
or Type assert each thing
或类型断言每一件事
// 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 });
See also https://github.com/Microsoft/TypeScript/issues/3755