Can TypeScript verify the types of string aliases during typing?

Consider the following code snippet:

type Firstname = string
type Surname  = string

const firstname: Firstname = "John";
const surname:Surname = "Smith"

function print(name: Firstname) {
    console.log(name)
}

/*
 * This should give a compile error
 */

print(surname);

How can we prevent passing a Surname type when the function specifically requires a Firstname?

Answer №1

If you're searching for something known as branded types, TypeScript determines type compatibility structurally. This means that aliases won't render types incompatible, but we can create structural differences by using an intersection type and a unique symbol:

type Firstname = string & { readonly brand?: unique symbol }
type Surname = string & { readonly brand?: unique symbol }

const firstname: Firstname = "John"; // A string can be assigned because the brand is optional
const surname: Surname = "Smith"

function print(name: Firstname) {
    console.log(name)
}

print(surname); // Error - unique symbol declarations are incompatible 

There may be different variations of this concept, but the underlying idea remains consistent. You may find similar answers helpful: guid definition, index and position , and others

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

Exploring methods to retrieve the status attribute of an Angular httpClient response

Here is the code snippet that I am working with: this.http.post(url, payload) .subscribe( (req:any)=>{ if(req.status != 200){ console.log('non 200 status'); The this.http in my code refers to a service tha ...

Unable to transfer object from Angular service to controller

I am currently utilizing a service to make a $http.get request for my object and then transfer it to my controller. Although the custom service (getService) successfully retrieves the data object and saves it in the responseObj.Announcement variable when ...

Changing the function to operate asynchronously

How can I convert the following code into an asynchronous function? It is currently returning referralUrl as undefined: controller async createReferralUrls() { this.referralUrl = await this.referralService.generateReferralUrl(this.userData.referral ...

Guide on navigating an array of objects using the provided keys as a starting point in Javascript/Typescript

Assuming I have an array of objects structured like this: const events: Array<{year: number, month: number, date: number}> = [ {year: 2020, month: 10, date: 13}, {year: 2021: month: 3, date: 12}, {year: 2021: month: 9, date: 6}, {year: 2021: mont ...

What is the best method to find a matching property in one array from another?

I am working with two arrays in TypeScript. The first one is a products array containing objects with product names and IDs, like this: const products = [ { product: 'prod_aaa', name: 'Starter' }, { product: 'prod_bbb&apos ...

When working with Typescript, an error may occur related to index types even though the constant object and its

I am struggling with understanding TypeScript, specifically when it comes to a problem I encountered. Hopefully, someone can shed some light on this for me. My issue revolves around a functional component that is responsible for displaying the correct com ...

Determine the Angular object's type even if it may be undefined

Currently diving into Angular and looking to create a method that can determine if an object is of type Dog (identified by a woof property). This is the code snippet I have put together so far: export class SomeClass { public animal?: Dog | Cat; ... ...

Is it necessary to use StyleProp<style> in React-Native, or can I simply write the styles without it?

My usual writing style is as follows: interface _props{ style?: TextStyle, } However, I'm considering adding StyleProp. What do you think? interface _props{ style?: StyleProp<TextStyle>, } If so, what are the reasons for doing so? ...

What methods are available to me for creating a wrapper for an Angular Component that simply changes the component selector name?

Having experience with React, you can simplify a library component in your app by giving it a new name like this: const MyAppTable = (props) => <LibraryTable ...props />; I'm interested in achieving a similar result in Angular, but I'm ...

If a generic string argument is not specified as a string literal, it will not be narrowed unless it is the first argument

When the following code is executed, it works as intended and we can see that the arg variable is a string literal: const foo = <T extends string = string>(arg: T) => {}; foo('my string'); // const foo: <"my string">(arg ...

TypeScript Error 2304: Element 'div' is nowhere to be found - CRA TypeScript Template

I'm experiencing a problem in VSCode while working on the default create-react-app my-app --template typescript project. It seems to not recognize any HTML elements, as I keep getting the error cannot find name xxx, where 'xxx' represents th ...

Is there a way to programmatically control a Bootstrap Dropdown in Angular?

Need help with opening and closing a Dropdown in my View using my typescript class. Any suggestions on how to achieve this? Appreciate any assistance! <div ngbDropdown class="d-inline-block"> <button class="btn" id=&quo ...

How can I ensure my function waits for a promise to be resolved using Async / Await?

I'm running into an issue where I want my function to keep executing until the nextPageToken is null. The problem occurs when the function runs for the first time, it waits for the promise to resolve. However, if there is a nextPageToken present in th ...

Understanding the mechanism behind how the import statement knows to navigate to the package.json file

I find myself stuck in bed at the moment, and despite numerous Google searches with no clear answers, I have chosen to seek help here. Could someone please clarify how scoping works when using import in TypeScript and determining whether to check the pack ...

What is the process for creating a class in TypeScript?

Here is an example of the object structure I am working with: { "info" : { "title" : '123}, "details": [ {"desc": "d1"}, {"desc": "d2}] } I am currently in the process of defining ...

Creating a string within the component.html file in Angular

Currently, I am utilizing the @ngx Translate Service. Within a template, you can utilize it in the following manner, where 'stringName' represents a key within a JSON file: {{ 'stringName.subStringname' | translate }} The issue I am fa ...

Does this fall under the category of accepted practices for employing an effect in Angular?

I am working on integrating an Angular directive with a signal that receives values from a store selector. This signal is crucial for determining whether a button should be disabled or not. I'm curious about the best approach to listen to this signal ...

What is the best way to ensure complex types are properly initialized and functioning when declaring data within a vue.js module?

Utilizing a TypeScript class that I created called Budget to initialize data for a module has been proving to be challenging. When I attempt something like this: currBudget: {} = { id: 20, name: 'Chris' }; everything functions as expected. How ...

Node.js: The choice between returning the original Promise or creating a new Promise instance

Currently, I am in the process of refactoring a codebase that heavily relies on Promises. One approach I am considering is replacing the new Promise declaration with simply returning the initial Promise instead. However, I want to ensure that I am correctl ...

Is Typescript compatible with the AWS Amplify Express API?

I've been struggling to set up my Amplify API in TypeScript and then transpile it to JavaScript. I know it sounds like a simple process, but I could really use some guidance on how to do this effectively. So far, I haven't progressed beyond the ...