2

I am writing a set of TypeScript classes that use inheritance to maintain a "Type" hierarchy (for want of a better phrase).

Say for example I have a base class...

class Parent {
}

and then I derive other classes from this...

class Child extends Parent {
}

So far so good...but lets say, now I want to be able to assign something to my Child class directly, like so:

private xyz: Child = "Foo Bar";

TypeScript currently throws up a compiler/syntax error...

Cannot convert string to Child

If I can assign strings to String (which is equally, just a prototype, as is my Child class), how do I go about overloading the assignment operator of my class to accept strings?

EDIT: I tried this...

class Child extends Parent implements String {
}

...still, it does not have the desired effect.

Speaking from a C# background, I guess I'm trying to achieve the equivalent of...

public static implicit operator Child(string value
{
    return new Child(value);
}

1 Answer 1

2

In a class-based language you would normally accept parameters in the constructor, like this:

class Parent {
}

class Child extends Parent {
    constructor(private someProp: string) {
        super();
    }
}

var child = new Child("Foo Bar");
Sign up to request clarification or add additional context in comments.

2 Comments

Speaking from a C# background, is there no way you can do the equivalent of public static implicit operator Child(string value) {} ?
This feature doesn't exist in TypeScript at the moment - the implicit and explicit conversions are a neat feature in C#. You could suggest it to the TypeScript team: typescript.codeplex.com

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.