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.
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.
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.
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.
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.
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: {} }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With