为什么Typescript不会尊重我接口中返回对象的类型?
- 论坛
- 为什么Typescript不会尊重我接口中返回对象的类型?
29 浏览
为什么Typescript不会尊重我接口中返回对象的类型?
我创建了一个接口来表示函数的返回类型。然而,如果我将返回类型更改为意料之外的类型,TypeScript并没有像我期望的那样报错。以下是一个示例,您也可以在播放区中查看示例:
export interface ITest { id: string isLatest: boolean createdAt: number updatedAt: number } function testZero(): any { return { id: '123', isLatest: true, createdAt: '123', updatedAt: 456 } } function testOne(): ITest { return testZero() } function testTwo() { const res = testOne() console.log(res) } testTwo()
我收到的输出是:id: "123", isLatest: true, createdAt: "123", updatedAt: 456}
然而,我期望它不会运行,因为createdAt
应该是一个数字,而不是一个字符串。为什么即使类型与预期的接口不匹配,它仍然运行?