函数返回对象类型

时间:2019-06-01 15:11:43

标签: typescript

当我在Typescript中定义对象时,该对象不能具有未在其类型中指定的属性:

但是,当我定义一个返回对象的函数时,该对象可以具有比其类型中指定的属性更多的属性:

type Style = { color: string };
type IFunction = () => Style

const foo: Style = {
    color: "red",
    toto:"blue" // error yeah :)
}

const bar: IFunction = () => ({
    color: "red",
    toto:"blue"
})

如何指定我只想返回在对象类型中指定的属性,并且每当添加一些额外的属性时都想引发一个错误?

Typescript example here

编辑:我应该指定我不希望明确地告诉返回类型:

const bar: IFunction = ():Style => ({
    color: "red",
    toto:"blue"
})

实际上,我想对我的App中的每个React组件使用此代码,并且每次都指定这种类型确实很麻烦

1 个答案:

答案 0 :(得分:0)

尝试如下,明确说明函数的返回类型

type Style = { color: string };
type IFunction = () => Style;

const foo: Style = {
    color: "red",
    toto: "blue" // error yeah :)
};

const bar: IFunction = (): Style => ({
    color: "red",
    toto: "blue" // no error ??????
});

Property excessive checks在以下情况下也必须明确说明类型(自TypeScript 3.4 起),在Typescript 3.5中改进了联合类型的多余属性检查

function checkStyle(style: Style) {}

checkStyle({
    color: "red",
    toto: "blue" // cast to Style, no error yeah :(
} as Style);

let foo3 = {
    color: "red",
    toto: "blue" // no type annotation and no error yeah :(
};

checkStyle(foo3);

当TypeScript检查一个对象类型是否可分配给另一对象类型时,不抛出错误的原因是类型扩展。只要对象上存在color属性,TypeScript就会满意。

相关问题