Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript interface initialization

Tags:

oop

typescript

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:

  1. Create a simple implementation of ISimpleObject. I don't like this approach because it looks like boilerplate code to me
  2. don't initialize the object (I fear this could break something...):

    var x :IsimpleObject; x.bar = 'xxx'; callMethod(x);

  3. 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.

like image 233
Giacomo Tagliabue Avatar asked May 01 '14 16:05

Giacomo Tagliabue


People also ask

How do I initialize a TypeScript interface?

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.

Can TypeScript interface have implementation?

Interface as TypeInterface in TypeScript can be used to define a type and also to implement it in the class.

Can we set default value in interface TypeScript?

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.

What is TypeScript interface?

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.


1 Answers

Typescript2:

const simpleObject = {} as ISimpleObject; 
like image 136
sdrevk Avatar answered Sep 26 '22 12:09

sdrevk