简体   繁体   中英

using a interface to type a anonymous object in typescript

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.

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 :

在此输入图像描述

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: {} }

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 {} . ie 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
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM