How to usean Array of Strings in Typescript
In this approach, we are using an array of strings, and define a generic type `StringUnion<T extends string>` where `T` represents the string literals. This approach creates a union type from the elements of the array.
Example: We Define a generic ‘StringUnion` type accepting string literals. Creates an array of specific strings, then logs each element in a function taking the same type as an argument.
type StringUnion<T extends string> = T[];
type MyStringType = "HTML" | "CSS" | "Javascript";
const myStringArray: StringUnion<MyStringType> =
["HTML", "CSS", "Javascript"];
function resultFunction(language: StringUnion<MyStringType>): void {
language.forEach(languageItem => console.log(languageItem));
}
resultFunction(myStringArray);
Output:
[ 'HTML', 'CSS', 'Javascript' ]
[ 'HTML', 'CSS', 'Javascript' ]
[ 'HTML', 'CSS', 'Javascript' ]
How to Create Union of Generic Types that Extend String in TypeScript ?
Creating a union of generic types that extend string in TypeScript involves defining a type that accepts only string literals. This allows for the creation of a type that represents a specific set of strings, providing type safety and flexibility in code.
These are the following ways to do that:
Table of Content
- Using an Array of Strings
- Using a Mapped Type
- Using Conditional Types:
- Using Template Literal Types
- Using Type Aliases with Utility Types