【发布时间】:2019-10-21 11:38:39
【问题描述】:
我试图在一个地方描述具有特定部分类型返回值的功能接口。
我的界面IStore 只包含一个属性test。如果我将我的接口设置为某个函数foo,它还返回一个带有另一个属性的哈希图,打字稿会告诉“一切正常”。但是我需要得到 ts 错误,而来自foo 的返回值与Partial<IStore> 不严格匹配。在foo没有明确指示返回值
interface IStore {test: string;}
type IFunction<S> = (store: S) => Partial<S>;
// no ts errors. WHY?
// that's NO OK for me.
const foo1: IFunction<IStore> = () => ({
test: '',
test2: '' // why no errors in this row?
});
// ts error,
// it is working, but not my target case
const foo2: IFunction<IStore> = (): IStore => ({
test: '',
test2: '' // error here
});
// Meanwhile...
// no ts error
// that's OK
const foo3: IFunction<IStore> = () => ({
test: ''
});
// and...
// ts error: Type '{ test2: string; }' has no properties
// in common with type 'Partial<IStore>'
// that's OK
const foo4: IFunction<IStore> = () => ({
test2: ''
});
如果没有... (): IStore => ...,如何在“case 1”(foo1) 中从“case 2”(foo2) 得到错误?
【问题讨论】:
-
这是 TypeScript 中的 known issue。函数表达式返回时不会发生过多的属性检查,尽管人们期望它会发生。 TypeScript 没有直接的方法来指定 exact types,这正是您想要的。有一些方法可以获得类似的行为,但它们可能需要您使用像
const foo = asIFunctionIstore(...)这样的辅助函数,而不是您想要的const foo: IFunction<IStore> = ...。不确定您是否会对这样的解决方案感兴趣
标签: typescript interface typescript-typings