HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / TypeScript / String Literal Types

String Literal Types

In TypeScript, string literals allow you to specify the exact value a string must have in it’s lifespan. You can assume it a form as ‘string based enum’ which also is named group of string constants.

Syntax

Use ‘pipe’ symbol between different allowed string values.

type myVar = "value1" | "value2" | "value3" | "value4";	//upto N values

//For example

type AppStatus = "ACTIVE" | "INACTIVE" | "ONHOLD";		

String Literal types example

Let’s see how we can use string literal and how we cannot.

  1. Variable Assignment

    You can assign only allowed values to literal type variable. Else it will be compile time error.

    type AppStatus = "ACTIVE" | "INACTIVE" | "ONHOLD";
    
    let currStatus: AppStatus;
    
    currStatus = "ACTIVE";		//OK
    
    currStatus = "DELETED";		//Error - Type '"DELETED"' is not 
    							//assignable to type 'AppStatus'
    
  2. Function Parameter

    You can pass only allowed values to literal type argument. Else it will be compile time error.

    type AppStatus = "ACTIVE" | "INACTIVE" | "ONHOLD";
    
    function showMe(currentStatus: AppStatus): void {
    	console.log(currentStatus);
    }
    
    showMe('ACTIVE');	//OK - Print 'ACTIVE'
    
    showMe('DELETED');	//Compile time Error
    

Drop me your questions in comments section.

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

TypeScript Tutorial

  • TypeScript – Introduction
  • TypeScript – Types
  • TypeScript – Union Types
  • TypeScript – String Literal Types
  • TypeScript – var, let and const
  • TypeScript – Template Strings
  • TypeScript – Arithmetic Operators
  • TypeScript – Logical Operators
  • TypeScript – Comparison Operators
  • TypeScript – ‘for…of’ Loop
  • TypeScript – Spread Operator
  • TypeScript – Arrays
  • TypeScript – Enums
  • TypeScript – Map
  • TypeScript – Set
  • TypeScript – Functions
  • TypeScript – Function Overloading
  • TypeScript – Transpiler
  • TypeScript – Truthy and falsy
  • TypeScript – == vs ===
  • TypeScript – undefined vs null
  • TypeScript – Variable Hoisting
  • TypeScript – tsconfig.json

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces