TypeScript's strict definition of aliases

In my API, I need to define a type for representing an iso datetime string. I want to ensure that not just any string can be assigned to it. I want the compiler to catch any invalid assignments so I can handle them appropriately. So in Golang, I would like something similar to this: type Time string

The following code is accepted in TS, but I want to prevent this assignment: const time: Time = "..."

type Time = string; 
const message: string = 'hello world';
const time: Time = message;

typescript playground

Edit 1:

By using the Json article below, I was able to restrict arbitrary strings from being passed to the Time type, although reverse assignment is still possible with no errors at

const someType: number = fourthOfJuly;

enum DateStrBrand { }
export type DateStr = string & DateStrBrand;

const fourthOfJuly = toDateStr('2017-07-04');
const someType: string = fourthOfJuly;


function checkValidDateStr(str: string): str is DateStr {
  return str.match(/^\d{4}-\d{2}-\d{2}$/) !== null;
}

export function toDateStr(date: string): DateStr {
  if (typeof date === 'string') {
    if (checkValidDateStr(date)) {
      return date;
    } else {
      throw new Error(`Invalid date string: ${date}`);
    }
  }
  throw new Error(`Shouldn't get here (invalid toDateStr provided): ${date}`);
}

typescript playground

Answer №1

After reading @jcalz's insights, I developed the following solution with assistance from the provided resource.

export interface DateStr extends String {
  ____dateStrBrand: string; // Adding a brand to avoid type errors
}

// Ensuring safety!
var fooId: Time = "..."; // This will throw an error
fooId = "..." as any; // This is acceptable

// Accessing the base string if needed
var str: string;
str = fooId; // This will result in an error
str = fooId as any; // This is allowed

Answer №2

Your safest bet would be to utilize a branded string in combination with a typeguard.

I'm thankful that I decided to search online before diving into a detailed explanation, as I stumbled upon Patrick Bacon's fantastic resource on this topic.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Which is better: using multiple makeStyles or just one in Material UI?

Uncertain about the best approach in this situation. Is it acceptable to generate styles using makeStyles for each component individually, or would it be better to create one in the base component and simply pass down class names? ...

angucomplete-alto automatically fills in data based on another input

Having two autocomplete select boxes with a unique feature has been quite interesting. The first input accepts a code that is related to a label, autofilling the second input with the corresponding object once the code is selected in the first input. Howev ...

Transform JSON into an Array and generate a new Array from a collection of Arrays

I'm struggling with generating a table in Angular2 from JSON data because I need to pivot the information, but my usual method doesn't seem to work for this scenario. Below is an excerpt of the JSON data I am working with: [ { "ValueDate" ...

Employing ng-show and other related features within directive "A"

After browsing through similar inquiries, I am still unable to comprehend the solution. If I have a directive available at this link: http://pastebin.com/QtAzGv62 and now need to incorporate the functionality of "ng-show" (or any other standard angular di ...

Applying a switch case to dynamically alter the background image using CSS depending on the specific case

Currently, I am working on implementing a feature that allows users to switch the background image of the cropper based on the crop operation ratios they select (SQUARE/PORTRAIT/LANDSCAPE). To achieve this, I plan to set three variables representing each ...

Personalized PHP Error Handler incorporating Notification

I am seeking a way to display PHP error information in a JavaScript alert box. I have attempted to utilize PHP's set_error_handler(), but I am encountering issues where it only displays the default error and prevents me from choosing other options. s ...

Dispatch an angular POST Request

I am facing an issue where Angular is sending a GET request instead of a POST request when I want to send a post request. The code for my Angular request is as follows: $http({ method: 'POST', url: pages_url, params: { ...

The tooltip for the Google+ button stopped working

After setting up my Portfolio, I added a Google+ button. However, the page lacks styling and there seems to be an issue with the tooltip causing delays. Can anyone help me identify where the problem lies? ...

Vue app showcasing array items through search upon button pressing

As I delve into learning Vue Js, I've encountered a bit of confusion. My goal is to showcase array elements from a Rest API based on the specific ID being searched for. For example: within my Json File are various individuals with unique IDs, and when ...

How to make a list with a scroll bar in an HTML table cell

Having trouble creating a scrollable list in a dynamically appended HTML table cell using JavaScript? You're not alone. Even after assigning the list to the cell parent, it seems that the list is not behaving as expected - it's not scrollable and ...

Transferring shapes from a two-dimensional equirectangular view to surfaces in A-Frame

Currently, my goal is to create a hotspot editor for 360-degree images using A-Frame. The concept behind this project involves allowing users to draw on an equirectangular panorama and then having the tool convert those drawings into planes using THREE.Sh ...

The object's value might be undefined, despite having null checks in place

Currently using Typescript 4.0.5 and encountering a persistent Object is possibly undefined error message My local state includes a .csv file uploaded by the user const [currentLine, setCurrentLine] = useState<File>(); The useEffect function monit ...

Having difficulty placing markers on a Mapbox map using mapbox-gl.js

I've been working tirelessly to incorporate markers onto a mapbox map using mapbox-gl-js with typescript. Despite following various tutorials from the mapbox site, I haven't been able to get it to work. mapboxgl.accessToken = 'mykey&apo ...

Employ the express platform to refrain from responding to particular inquiries

Is there a way for my server to not respond at all when receiving a specific user-agent in the request header, while still serving HTML normally for other browsers? I tried different methods like using res.status(404).end() and res.destroy(), but they did ...

Verify if the screen is in full view by monitoring document.fullscreenElement within Vue3

Is there a way to determine when the document is in fullscreen mode? I attempted to monitor document.fullscreen with the following code, but it was not successful: watch(document.fullscreenElement, (newValue) => { fullScreenActivated.value = newValue ...

Attempting to transfer information from a JSON file to a Netflix-inspired platform

Images I am currently working on integrating data from my json file export const products = [ { name: 'iPhone 11', image: '/assets/images (7).jpeg', time: '1 hour 14mins', age: '+16&apo ...

How can I stop a browser from refreshing when I click the mouse?

After taking steps to prevent the browser back button from functioning by clearing history and disabling key events for page refresh, I am now seeking a way to also stop mouse clicks on the browser's refresh button. Can anyone offer assistance with th ...

Use Node and Express with JavaScript to store HTML form data in JSON format within a .json file

Just starting out with node and express. I am capturing user input from an HTML form and attempting to append or push it in a .json file. I tried using the jsonfile npm package but the data is not being stored in an array format in the JSON file. Here is ...

Is there a way to grab the inner content of an e-mail link by right-clicking on it?

I am currently developing a Chrome Extension that functions similarly to the "Search on Google" feature when you right-click on selected text. However, I am facing an issue with making it work when right-clicking on a mailto: email link. How can I extract ...

The webpage becomes unresponsive and gets stuck when sending a stream of requests to the web server via ajax

I am currently working on creating a signal on the webpage that displays either a green or red color based on values retrieved from a database. However, when I send a request after 10 seconds, the page appears to freeze and becomes unresponsive. I am strug ...