从 TypeScript 1.6 开始,对象字面量中的属性在分配给它们的类型中没有对应的属性会被标记为错误。
通常,此错误意味着您的代码或定义文件中存在错误(通常是拼写错误)。在这种情况下,正确的解决方法是修复错字。在问题中,属性callbackOnLoactionHash 不正确,应该是callbackOnLocationHash(注意“位置”的拼写错误)。
此更改还需要对定义文件进行一些更新,因此您应该为正在使用的任何库获取最新版本的 .d.ts。
例子:
interface TextOptions {
alignment?: string;
color?: string;
padding?: number;
}
function drawText(opts: TextOptions) { ... }
drawText({ align: 'center' }); // Error, no property 'align' in 'TextOptions'
但我是故意的
在某些情况下,您可能打算在对象中添加额外的属性。根据您的操作,有几个适当的修复方法
仅对某些属性进行类型检查
有时您想确保一些东西存在且类型正确,但出于任何原因都打算拥有额外的属性。类型断言(<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;
这些属性,也许还有更多
某些 API 采用对象并动态迭代其键,但具有需要为特定类型的“特殊”键。向类型添加字符串索引器将禁用额外的属性检查
之前
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' };
}
这里想到了两个好的解决方案
为x指定一个封闭集
// Removes all errors
let x: Dog|Cat|Horse;
或键入断言每件事
// For each initialization
x = { move: 'doggy paddle', woof: 'bark' } as Dog;
这种类型有时是开放的,有时不是
使用交集类型解决“数据模型”问题的干净解决方案:
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