Typescript 在函数类型中定义返回类型时,键入脚本附加返回属性
以下示例很好地说明了我的问题:Typescript 在函数类型中定义返回类型时,键入脚本附加返回属性,typescript,Typescript,以下示例很好地说明了我的问题: 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
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;
但这会产生错误“对象文字可能只指定已知属性,并且“z”不存在于类型“Position”中”
最后一个示例
const position:position=update()
实际上很好,因为update()
返回扩展position
的内容。您可以更严格地说const position:{x:number}=update()
,这也没关系,只要该值至少有{x:number}
。变量位置
中的对象仍将具有y
和z
属性,但在尝试访问它们时会出现错误,因为typescript不知道这些属性。可能值得链接到手册文档中有关它们的内容
const position2: Position = { x: 0, y: 0, z: 0 };