Search code examples
angulartypescripttype-conversiontype-assertion

Typescript convert string[] to string


I have an Angular 5 application and i have a candidate object which has a string[] property, specified in the interface it implements. The actual value of the property is being retrieved from the template, as an input string. This is the problem. The object needs to be saved into the database as an array of strings like this:

{ candidate.skills: ["c++", "java", "etc"] }

However, the value from the input field in the template comes as a string. But typescript thinks it is a string[] as specified in the interface of the object. So, i cant split the candidate.skills into an array.

Is there a way to do this ? If so, i didnt find it yet.


Solution

  • You can in the interface specify the type as string or array if you want to.

    skills: string|string[];
    

    EDIT

    As mentioned in the comments, you might have to cast your variable to do certain operations only available to the specific type:

    // Convert from string to string[]
    this.candidate.skills = (<string>this.candidate.skills).split(', ');