My level of typescript is 'ABSOLUTE BEGINNER' but I have a good OOP background. I am building an with typescript that reference an external t.ds
library that contains the following interface:
interface ISimpleObject { foo: string; bar?: any; }
Now, if I want to call a method that has an IRequestConfig parameter, how do I create one? I can see different options:
don't initialize the object (I fear this could break something...):
var x :IsimpleObject; x.bar = 'xxx'; callMethod(x);
Cast a pojo:
var x :IsimpleObject = <IsimpleObject>{foo: 'yyy', bar:'xxx'};
I don't like this approach either because it doesn't enforce type safety...
I guess this is a fairly trivial question and I am missing something trivial about typescript.
Use a type assertion to initialize a typed, empty object using an interface in TypeScript, e.g. const emp1 = {} as MyInterface . You can access or set any properties on the object, as long as they exist on the interface and are compatible with the corresponding types.
Interface as TypeInterface in TypeScript can be used to define a type and also to implement it in the class.
To set default values for an interface in TypeScript, create an initializer function, which defines the default values for the type and use the spread syntax (...) to override the defaults with user-provided values.
In TypeScript, an interface is an abstract type that tells the compiler which property names a given object can have. TypeScript creates implicit interfaces when you define an object with properties. It starts by looking at the object's property name and data type using TypeScript's type inference abilities.
Typescript2:
const simpleObject = {} as ISimpleObject;
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