What is the capability of dynamically generating an index in Typescript?

Can you explain why the Typescript compiler successfully compiles this code snippet?

type O = {
  name: string
  city: string
}

function returnString(s: string) {
  return s
}

let o1: O = {
  name: "Marc",
  city: "Paris",
  [returnString("random")]: "London",
}

Answer №1

What is surprising about this?

The reason why the code passes is because it is valid traditional JavaScript starting from ES2015.

Even if it wasn't directly supported in JavaScript, since this code can easily be converted to JavaScript that does not have computed key values support, and it's a practical and convenient feature to have... why not embrace it?

Written in ES2015:

"use strict";
function returnString(s) {
    return s;
}
let o1 = {
    name: "Marc",
    city: "Paris",
    [returnString("random")]: "London",
};

Converted to ES5:

"use strict";
var _a;
function returnString(s) {
    return s;
}
var o1 = (_a = {
        name: "Marc",
        city: "Paris"
    },
    _a[returnString("random")] = "London",
    _a);

Answer №2

Exploring the intricacies of the : never type in TypeScript can lead to a deeper understanding of discriminated unions, a more advanced concept in the language.

While this explanation may not cover everything, it serves as a hint to help grasp the issue at hand and the potential limitations with string return values.

type O = {
  name: string
  city: string
}

declare const neverValue: never;

// Uncommenting this will result in failure
// function returnStringS(s: string): 's' {
//     return 's';
// }

// These examples will work without any issues
function returnStringS(s: string): string {
  return 's';
}

function returnStringS(s: string): string {
  return s;
}


let o1: O = {
  name: "Marc",
  city: "Paris",
  [returnStringS("random")]: "London",
}

let o2: O = {
  name: "Marc",
  city: "Paris",
  [returnStringS("random")]: "London",
}

const some2: O = {
  name: "Marc",
  city: "Paris",
  [neverValue]: "London"
}

For further insight into the TypeScript never type and its implications, refer to the documentation on TS never type.

The never type is a subtype of every type but no type is a subtype of never (except never itself). Even any type isn't assignable to never.

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

Using Iframe for WooCommerce integration and implementing Facebook login within an Ionic application

I have created an Ionic application that includes an iframe from a Wordpress website. Here is the code snippet from my home.page.ts file: import { Component } from '@angular/core'; import { DomSanitizer } from "@angular/platform-browser"; @Com ...

Tips for converting API data to DTO (Data Transfer Object) using TypeScript

Here is an array of vehicles with their details. export const fetchDataFromApi = () => { return [ { vehicleId: 1, vehicleType: 'car', seats: 4, wheelType: 'summer', updatedAt: new Date().toISOString }, { vehicleId: 2, vehic ...

Extending injections in Angular 5 by inheriting from a base class

I have created a class with the following structure: @Injectable FooService { constructor(protected _bar:BarService){ } } Then, I extended this class as shown below: @Injectable ExtFooService extends FooService { constructor(_bar:BarServi ...

Tips for looping through a Set in TypeScript

What is the best way to loop through a set in TypeScript? Using for..of does not seem to work properly: 'Set<string>' is neither an array nor a string type Using .forEach is not ideal since it obscures the context of this. I would rather ...

Trying out the results of angular services

Seeking assistance in understanding the current situation: I believe a simple tour of heroes app would be helpful in clarifying, I am looking to set up some tests using Jest to verify if the behavior of a service remains consistent over time. This is ho ...

Enhancing systemjs-builder with DefinitelyTyped

Is there a dedicated TypeScript definition file for systemjs-builder available? https://github.com/systemjs/builder I encountered an issue where the systemjs.d.ts file does not seem to cover it, leading to a "cannot find module" error when trying to impor ...

How can one define a getter within an interface?

One of my classes is structured like this (only showing a portion here): export class LinkedListNode<t> extends windward.WrObject implements ILinkedListNode<t> { public get next(): LinkedListNode<t> { return this._next === thi ...

The term "primordials is not defined" is a common error

Whenever I attempt to run Gulp using the task runner, I am encountering this error message. I suspect it may be due to updating my npm project, but I'm unsure about how to resolve it. Should I try installing a different version of npm? >Failed to r ...

how to send both the useState setter and object as props to a child component in React using TypeScript

Having an issue with passing useState setter and object (both together) to the child component. Successfully passed the object by spreading it like this {...object}, but unsure of the syntax to pass the setter along as well. Here's a code example: < ...

The CSS styles are functioning correctly in index.html, but they are not applying properly in the component.html

When the UI Element is clicked, it should add the class "open" to the list item (li), causing it to open in a collapsed state. However, this functionality does not seem to be working in the xxx.component.html file. Screenshot [] ...

Enhancing Twilio LocalVideoTrack with custom start and stop event handling

Is it possible to customize the events triggered when a video starts or stops playing? I attempted the code below, but unfortunately, it did not yield any results: this.videoTrack = screenTrack as LocalVideoTrack; this.videoTrack.stopped = function (eve ...

Issue encountered while trying to iterate through an observable: Object does not have the capability to utilize the 'forEach' property or method

I am currently following the pattern outlined in the hero.service.ts file, which can be found at this link: https://angular.io/docs/ts/latest/guide/server-communication.html The Observable documentation I referenced is available here: When examining my c ...

Is it possible to declare two global variables with the same name in Angular?

There are two global variables that come from different third-party files with the same name. Previously, I would use them like this: declare var someVar; But now, how can I use both of these variables? declare var someVar; declare var someVar; Is th ...

Building a dropdown menu component in react native

Looking to implement a dropdown menu in React Native using TypeScript. Any suggestions on how to achieve this for both iOS and Android platforms? Check out this example of a dropdown menu ...

Error: The function to create deep copies of objects is not working properly due to TypeError: Object(...) is not a

Encountering a TypeError: Object(...) is not a function in the following situation: To set up the state of a component with a specific Article (to be fetched from the backend in componentDidMount), I am implementing this approach // ArticlePage.tsx import ...

Is there a way to include the present date and time within a mat-form-field component in Angular?

I'm working on a mat-form-field to display the current time inside an input field. I've managed to insert it, but I'm struggling with the styling. Here's the snippet of code I'm using: <mat-label>Filing Time:</mat-label> ...

Steps to define a JavaScript mixin in VueJS

Currently, I am working on a Vue project with TypeScript and in need of using a mixin from a third-party library written in JavaScript. How can I create a .d.ts file to help TypeScript recognize the functions defined in the mixin? I have attempted the fol ...

What is the proper way to address the error message regarding requestAnimationFrame exceeding the permitted time limit?

My Angular application is quite complex and relies heavily on pure cesium. Upon startup, I am encountering numerous warnings such as: Violation ‘requestAnimationFrame’ handler took 742ms. Violation ‘load’ handler took 80ms. I attempted to resolve ...

Node.js - Creating seamless integration between Sequelize model JS and controller TS

Having trouble making my User.js model recognized inside my UserController.ts with sequelize in TypeScript. Edit: Unable to change the file extensions for these files. In the await User.findAll() part, an error occurs when running on the server, stating ...

What is the best way to develop a function that can take in either a promise or a value and output the same type as the input parameter?

I'm currently working on a TypeScript function that can handle either an A type or a Promise<A>. In this case, A represents a specific concrete type, and the function should return the same type. If it receives a Promise<A>, then the retur ...