打字稿。为什么没有严格执行功能接口中描述的“返回值”类型?

时间:2019-06-05 23:36:06

标签: typescript interface typescript-typings

我试图用一个地方描述返回值的特定部分类型的功能接口。

我的界面.rating, .container { display: flex; list-style-type: none; margin: 0; } .rating li { width: 1rem; height: 1rem; border: 1px solid #ddd; border-radius: .5rem; margin: .1rem; } .fill { background-color: #eee; }仅包含一个属性<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <div v-for="n in reverseKeys(5)" :key="n"> <div class="container"> <span>{{ n + 1 }}</span> <ul class="rating"> <li v-for="key in 5" :class="{ fill: key <= n + 1 }" :key="key" /> </ul> </div> </div> </div>。如果我将接口设置为某个函数IStore,该函数还返回具有另一个属性的哈希图,则打字稿会告诉“一切正常”。但是我需要得到ts错误,而test的返回值与foo并不严格匹配。在没有明确指示的情况下,foo

上的返回值
Partial<IStore>

如何在没有foo的情况下从“情况1”(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: '' }); )的“情况2”(foo2)中获取错误?

1 个答案:

答案 0 :(得分:0)

Typescript有时会应用严格的属性检查,有时却不会。当应用冒号时,它将始终执行严格的属性检查(函数参数除外)。如果未应用冒号,则将比较结构以查看是否与别名的结构匹配,如果为true,则类型兼容,这是结构类型化的核心。此冒号检查适用于范围内最近的冒号。

当将冒号应用于ReturnType时,IStore或Partial只能具有{test:string}或{};但绝不要多余的属性。 I.E

const foo2 = (): Partial<IStore> => ({}); // is allowed but...
const foo2 = (): Partial<IStore> => ({notALlowed: true}); // not allowed

当不应用冒号时,它将执行结构类型检查,并关闭多余的属性,这是函数的类型别名的情况。

type IFunction<S> = (store: S) => Partial<S>;


const foo1: IFunction<IStore> = () => ({
  test: '',
  test2: '' // why no errors in this row?
});

现在可能会有些混乱,因为两个代码片段都实现了一个冒号,但是区别在于冒号的位置,对于函数,左边的冒号只会对函数参数进行严格的属性检查,而不会ReturnType。

相关问题