'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 1:[1]

The interface that i implement:

export class Candidate {
id: number;
name: string;
skills: string|string[]; }

In the component i try to upload my data through a service. The code in the component.ts:

import { Component, OnInit } from '@angular/core';
import { CandidatesService } from '../candidates.service';
import { Validators } from '@angular/forms';
import { Observable } from 'rxjs/Observable';

import { Candidate } from '../candidate';

@Component({
  selector: 'app-candidates-adding',
  templateUrl: './candidates-adding.component.html',
  styleUrls: ['./candidates-adding.component.css']
})
export class CandidatesAddingComponent implements OnInit {
  candidate: Candidate = new Candidate();

  constructor(private candidatesService: CandidatesService) { }

  ngOnInit() {

  }

  saveCandidate(): void {
    if(this.candidate.skills.indexOf(', ') >= 0) {
      this.candidate.skills = this.candidate.skills.split(', '); 
    }
    this.candidatesService.addCandidate(this.candidate).subscribe();
  }
}

And in the template:

<input [(ngModel)]="candidate.name" placeholder="name" minlength="4">
<input [(ngModel)]="candidate.skills" placeholder="name" minlength="1">
<button (click)="saveCandidate()">Adauga candidat</button>

Solution 2:[2]

I also had a similar problem, I was using typescript v.4.4.3.

this.candidate.skills = ((this.candidate.skills as unknown) as string).split(',')

so, first I set it to unknown and then to the type I want (here, for example, to string), and that's work for me.

Solution 3:[3]

I got here trying to convert a string|string[] to an int. I found 3 solutions.

const trouble: string|string[] = "1234"
const id = Number(trouble)
const id = parseInt(trouble.toString())
const id = parseInt(trouble.toString(), 10)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gabriel
Solution 2
Solution 3 Spencer5051