using a interface to type a anonymous object in typescript

旧城冷巷雨未停 提交于 2019-12-10 12:49:37

问题


I have a Interface IBase and a variable that contains a few other objects (in the sample i just added base for a better demonstration)

interface IBase {
    height?:number;
    width?:number;
}

var element = {
    base: {

    }
}

How can I say that the object that the varable element.base has is from the type IBase? I know that I could create a type for the element variable that contains the types of base etc, but is that also a possibility to type that scenario without doing so.


回答1:


Van den Brink's answer is good. Just as a demo another option :

var element = {
    base: <IBase> {

    }
}

This will give the desired intellisense as well :




回答2:


If you change the declaration of var element to the following it knows what base is:

var element: { base: IBase; } = {
    base: {
    }
}

Note: you can also create a new interface for it like this which makes it a bit more reusable: interface IElement { base: IBase; } and then use it like here: var element: IElement = { base: {} }




回答3:


You have accidentally caused yourself a problem with your interface declaration. It is a subtle one that you will come across with structurally typed languages.

interface IBase {
    height?:number;
    width?:number;
}

Because all of the properties are optional, the interface is essentially {}. i.e. any object satisfies this interface. That's too general to be useful in most cases.

For example, it is perfectly acceptable to do this:

var x: IBase = {
    a: 'efsdsdf',
    v: 'sdfdsf' 
};

I think you'll agree that really this object is not useful anywhere I wanted to use an IBase object.

With this out of the way, you may find the most graceful solution is to create an interface that matches your element definition.

interface IElement {
    base: {
        height?:number;
        width?:number;
    }
}

var element: IElement = {
    base: {
        height: 4
    }
}



回答4:


The excellent answer from @basarat now needs a little updating; using the angle brackets now produces a tslint error:

[tslint] Type assertion using the '<>' syntax is forbidden. Use the 'as' syntax instead. (no-angle-bracket-type-assertion)

The solution is a simple one:

const element = {
    base: {} as IBase
}

This also provides the intellisense (auto-complete) that you'd want as well.



来源:https://stackoverflow.com/questions/24264681/using-a-interface-to-type-a-anonymous-object-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!