简体   繁体   English

在函数类型中定义返回类型时打字稿额外的返回属性

[英]Typescript extra return properties when defining return type in function type

The following example illustrates my issue pretty well:以下示例很好地说明了我的问题:

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. 
                            

What if I want to type this functions in a separate file?如果我想在单独的文件中键入这些函数怎么办? Other than adding the return type to the actual function.除了将返回类型添加到实际函数之外。

When you declare that an object must be of an interface, you are saying that it must have at least those properties, not only those properties.当你声明一个对象必须是一个接口时,你是说它必须至少有那些属性,而不仅仅是那些属性。

Typescript will complain when you are creating an object from scratch (aka an object literal) with properties that are not known to the interface, but if the object is a variable then you won't get any error when using it to fulfill an interface.当您从头开始创建具有接口未知属性的对象(也称为对象字面量)时,Typescript 会抱怨,但如果对象是变量,那么在使用它来实现接口时不会出现任何错误。

This is ok:还行吧:

const xyz = { x: 0, y: 0, z: 0 };

const position1: Position = xyz;

But this gives error "Object literal may only specify known properties, and 'z' does not exist in type 'Position'"但这会产生错误“对象文字可能只指定已知属性,而‘位置’类型中不存在‘z’”

const position2: Position = { x: 0, y: 0, z: 0 };

Your final example const position: Position = update() is actually fine because update() returns something that extends Position .您的最后一个示例const position: Position = update()实际上很好,因为update()返回扩展Position You could be even more restrictive and say const position: {x: number} = update() and that's fine too, as long at the value has at least {x: number} .你可以更const position: {x: number} = update() ,这也很好,只要值至少有{x: number} The object in your variable position will still have y and z properties, but you'll get an error when trying to access them because typescript doesn't know about them.变量position的对象仍然具有yz属性,但是在尝试访问它们时会出现错误,因为 typescript 不知道它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM