Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 495
Safari Avatar asked Jun 17 '14 13:06

Safari


People also ask

Can I use an interface as type TypeScript?

TypeScript Interface TypeTypeScript allows you to specifically type an object using an interface that can be reused by multiple objects. To create an interface, use the interface keyword followed by the interface name and the typed object.

How do I create an anonymous class in TypeScript?

Create anonymous class extends superclass via class extends ? test('anonymous class extends superclass by `class extends ?`', () => { let stub = jest. fn(); let AntTask: {new(name: string): Task} = class extends Task { //anonymous class auto inherit its superclass constructor if you don't declare a constructor here.

How do you declare an anonymous object?

Typically, when you use an anonymous type to initialize a variable, you declare the variable as an implicitly typed local variable by using var. The type name cannot be specified in the variable declaration because only the compiler has access to the underlying name of the anonymous type.

How do you define anonymous type?

Essentially an anonymous type is a reference type and can be defined using the var keyword. You can have one or more properties in an anonymous type but all of them are read-only. In contrast to a C# class, an anonymous type cannot have a field or a method — it can only have properties.


2 Answers

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 :

enter image description here

like image 119
basarat Avatar answered Sep 29 '22 20:09

basarat


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

like image 43
Dick van den Brink Avatar answered Sep 29 '22 19:09

Dick van den Brink