1

Is it possible to inline initialize an array of the interface type IFooFace with different specific implementations? Or is it not possible and I have to initialize my objects before the array and then just pass them in?

This is how I can do it in C#:

public interface IFooFace
{
    int Id { get; }
}

public class Bar : IFooFace
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Zar : IFooFace
{
    public int Id { get; set; }
    public string MegaName { get; set; }
}

internal class Program
{
    public static IFooFace[] Data =
    {
        new Bar
        {
            Id = 0,
            Name = "first"
        },
        new Zar
        {
            Id = 1,
            MegaName = "meeeega"
        }
    };
}

And this is what I tried in TypeScript:

export interface IFooFace {
  id: number;   
}

export class Bar implements IFooFace {
    public id: number; 
    public name: string;
    // a lot of more properties
}

export class Zar implements IFooFace {
    public id: number; 
    public megaName: string;
    // a lot of more properties 
}

var Data : IFooFace[] =  [
    // how to initialize my objects here? like in C#?

    // this won't work:

    // new Bar(){
    //     id: 0,
    //     name: "first"
    // },
    // new Zar() {
    //     id: 1,
    //     megaName: "meeeeega"
    // }



    // this also doesn't work:
    // {
    //     id: 0,
    //     name: "first"
    // },
    //  {
    //     id: 1,
    //     megaName: "meeeeega"
    // }    
]; 

1 Answer 1

1

No, TypeScript does not have object initializers. @RyanCavanaugh shows possible solution in TS:

class MyClass {
  constructor(initializers: ...) { ... }
}

var x = new MyClass({field1: 'asd', 'field2: 'fgh' });
Sign up to request clarification or add additional context in comments.

1 Comment

wow... I didn't even realize that there aren't any object initializers at all - I always thought it worked when you just do var bla : Foo { ...} but if you look with instance of later it's not even an instance of Foo but instead of object...I must say I'm kinda disappointed... thanks anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.