TypeScript 3.4+

TypeScript version 3.4 has introduced so-called **const contexts**, which is a way to declare a tuple type as immutable and get the narrow literal type directly (without the need to call a function like shown below in the 3.0 solution).

With this new syntax, we get this nice concise solution:

const furniture = ['chair', 'table', 'lamp'] as const;
type Furniture = typeof furniture[number];

More about the new const contexts is found in this PR as well as in the release notes.

TypeScript 3.0+

With the use of generic rest parameters, there is a way to correctly infer string[] as a literal tuple type and then get the union type of the literals.

It goes like this:

const tuple = <T extends string[]>(...args: T) => args;
const furniture = tuple('chair', 'table', 'lamp');
type Furniture = typeof furniture[number];

More about generic rest parameters

Answer from ggradnig on Stack Overflow
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ typescript โ€บ typescript_array_tostring.htm
TypeScript - Array toString()
Returns a string representing the array. var arr = new Array("orange", "mango", "banana", "sugar"); var str = arr.toString(); console.log("Returned string is : " + str );
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ typescript โ€บ typescript-array-tostring-method
TypeScript Array toString() Method - GeeksforGeeks
July 12, 2024 - The Array.toString() method in TypeScript is a built-in function used to convert an array and its elements into a string representation.
Discussions

typescript - convert string to a string Array in javascript - Stack Overflow
Sorry , please bare with me , ah I would just like to ask for the terminology and how do we implement or convert a string into something like below. I am not sure if that is string array or somethi... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Create simple text string from array typescript
I have some array of strings like this const doc = ['TEST', 'TEST1','TEST2'] What I need is to make function that I will create simple string from doc, that will have some different text. If ther... More on stackoverflow.com
๐ŸŒ stackoverflow.com
string - TypeScript - Array toString() - Stack Overflow
Communities for your favorite technologies. Explore all Collectives ยท Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
๐ŸŒ stackoverflow.com
December 21, 2021
Convert an array of object to the array of string in TypeScript
Using lodash I need to convert an array of object to the array of string. More on stackoverflow.com
๐ŸŒ stackoverflow.com
Top answer
1 of 4
384

TypeScript 3.4+

TypeScript version 3.4 has introduced so-called **const contexts**, which is a way to declare a tuple type as immutable and get the narrow literal type directly (without the need to call a function like shown below in the 3.0 solution).

With this new syntax, we get this nice concise solution:

const furniture = ['chair', 'table', 'lamp'] as const;
type Furniture = typeof furniture[number];

More about the new const contexts is found in this PR as well as in the release notes.

TypeScript 3.0+

With the use of generic rest parameters, there is a way to correctly infer string[] as a literal tuple type and then get the union type of the literals.

It goes like this:

const tuple = <T extends string[]>(...args: T) => args;
const furniture = tuple('chair', 'table', 'lamp');
type Furniture = typeof furniture[number];

More about generic rest parameters

2 of 4
22

This answer is out of date; see @ggradnig's answer.

The best available workaround:

const furnitureObj = { chair: 1, table: 1, lamp: 1 };
type Furniture = keyof typeof furnitureObj;
const furniture = Object.keys(furnitureObj) as Furniture[];

Ideally we could do this:

const furniture = ['chair', 'table', 'lamp'];
type Furniture = typeof furniture[number];

Unfortunately, today furniture is inferred as string[], which means Furniture is now also a string.

We can enforce the typing as a literal with a manual annotation, but it brings back the duplication:

const furniture = ["chair", "table", "lamp"] as ["chair", "table", "lamp"];
type Furniture = typeof furniture[number];

TypeScript issue #10195 tracks the ability to hint to TypeScript that the list should be inferred as a static tuple and not string[], so maybe in the future this will be possible.

๐ŸŒ
Educative
educative.io โ€บ answers โ€บ what-is-the-arraytostring-method-in-typescript
What is the array.toString() method in TypeScript?
The toString() method of an array in TypeScript is used to return the string representation of all the elements of the array.
๐ŸŒ
DEV Community
dev.to โ€บ mehmehmehlol โ€บ from-string-to-array-to-string-f67
From String to Array to String - DEV Community
April 23, 2021 - On the other hand, if there is only one element in the array, the single item will be returned as a string without separators, and if there are no elements, an empty string is returned. As mentioned, including an argument for the separator parameter is optional if you want the elements to be joined with a comma.
Find elsewhere
๐ŸŒ
Webdevtutor
webdevtutor.net โ€บ blog โ€บ typescript-string-array-tostring
How to Convert a TypeScript String Array to a Single String: A Comprehensive Guide
In this example, we're using the ... a TypeScript string array to a single string can be achieved using various methods, including toString(), join(), and reduce()....
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 70583940 โ€บ create-simple-text-string-from-array-typescript
Create simple text string from array typescript
Sign up to request clarification or add additional context in comments. ... You can use join for all but the last entry, and add the last entry with "and". I suppose for an empty array you would return something like "there is no doc":
๐ŸŒ
Webdevtutor
webdevtutor.net โ€บ blog โ€บ typescript-array-into-string
Converting TypeScript Array into String: A Comprehensive Guide
By using template literals, you can easily interpolate array elements and additional text to create a customized string representation. const array = ['red', 'green', 'blue']; const string = `Colors: ${array.join(', ')}`; console.log(string); // Output: "Colors: red, green, blue" Converting TypeScript arrays into strings is a common task in many applications.
Top answer
1 of 4
4

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(', ');
2 of 4
0

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>
๐ŸŒ
Melvin George
melvingeorge.me โ€บ blog โ€บ convert-array-into-string-literal-union-type-typescript
How to convert an array into string literal union type in TypeScript? | MELVIN GEORGE
April 25, 2021 - To convert an array of strings ... you can first define the array of strings then make the array as readonly using the as const keyword, and then use the typeof operator on all the values contained in the array....
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ typescript โ€บ typescript_array_join.htm
TypeScript - Array join()
join() method joins all the elements of an array into a string. separator โˆ’ Specifies a string to separate each element of the array. If omitted, the array elements are separated with a comma.
๐ŸŒ
ReqBin
reqbin.com โ€บ code โ€บ javascript โ€บ ot8wzla9 โ€บ javascript-array-to-string-example
How do I convert array to string in JavaScript?
November 21, 2023 - You can also create a multiline string, check if it starts or ends with another string, and get the length of a string. In JavaScript, you can convert an array to a string using the Array.join(separator) and array.toString() methods.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 70398103 โ€บ how-do-i-convert-an-any-array-to-a-string-array-containing-other-datatypes-insid
How do I convert an any array to a string array containing other datatypes inside in typescript?
As @Calz pointed out, you don't need to explicitly enter the type of the variable, as initialization is taking place at the time of declaration. ... let a; a = 5 console.log(typeof a) // number a = "string" console.log(typeof a) // string let b = 5 b = "some string"; // error as TypeScript blames that type string is not assignable to type number