【发布时间】:2021-07-16 12:16:55
【问题描述】:
Typescript 无法检查返回类型是否为嵌套对象。考虑下面的代码,即使函数 A 中的结果变量显然与输出类型不匹配,Typescript 也不会发出错误。
interface Input {
a: string;
b: number;
}
interface Output {
c: Omit<Input, 'a'>;
d: string;
}
function A(input: Input): Output {
const result = { c: {a: 'aaa', b: 3}, d: 'okay' };
// Expect to have an error since the result is not matched to Output
// but there's not errors
return result;
}
function B(input: Input): Output {
const result = "{ c: {a: 'aaa', b: 3}, d: 'okay' }";
// Work as expected
return result;
}
// But access a property will give us error.
const test = A({ a: 'a', b: 3 });
test.c.a
知道为什么会这样吗?
如果我们明确告诉 Typescript const result: Output = ...,它会给我们错误。但我不确定这是否是一个好习惯。还有其他方法可以使其按预期工作吗?
【问题讨论】:
-
为什么
const result = "{ c: {a: 'aaa', b: 3}, d: 'okay' }";中的值有引号? (我敢肯定你一秒钟前没有,是吗……?) -
这里是测试typescript是否进行类型检查。在函数 A 中,我返回一个对象,在函数 B 中,我返回一个字符串。 Typescript 确实在函数 B 中显示错误,因为 String 与输出类型不匹配。但是当涉及到一个对象时,Typescript 并没有显示任何错误。
-
是的,我把
A和B弄糊涂了。 -
我的错。它可以以更清晰的方式命名哈哈