下面的例子很好地说明了我的问题:
type Position = {
x: number
y: number
}
const update = (): Position => ({ x: 0, y: 0, z: 0 }) // 'z' does not exist in type 'Position', as it should.
type Update = () => Position
const update: Update = () => ({ x: 0, y: 0, z: 0 }) // that's fine?
const position: Position = update() // so is this, even though it is clearly wrong.
如果我想在一个单独的文件中键入这些函数,该怎么办?除了将返回类型添加到实际函数之外。
当您声明一个对象必须是一个接口时,您是说它必须至少有这些属性,而不是只有那些属性。
当你从头开始创建一个具有接口不知道的属性的对象(也称为对象文字(时,Typescript会抱怨,但如果该对象是一个变量,那么在使用它来实现接口时不会出现任何错误。
这没问题:
const xyz = { x: 0, y: 0, z: 0 };
const position1: Position = xyz;
但这给出了错误";对象文字只能指定已知的属性,并且类型"Position"中不存在"z";
const position2: Position = { x: 0, y: 0, z: 0 };
最后一个例子const position: Position = update()
实际上很好,因为update()
返回了一些扩展Position
的内容。你可以更严格地说const position: {x: number} = update()
,这也没关系,只要值至少有{x: number}
。变量position
中的对象仍将具有y
和z
属性,但在尝试访问它们时会出错,因为typescript不知道它们。