Using Typescript, you can specify an array of type <T> within an object

Having a background in JS, I am currently exploring TS.

My goal is to create an object with a single field, which is an array of strings, while ensuring strong typing.

let container = {
  items: ['Item 1']
}

container.items[0] = 3; // This is incorrect

Although providing an initial value works, what if I want to leave items empty? Here's an example:

let container = {
  items<String>: []
}

container.items.push(3) // This is wrong
container.items.push('abc') // This is correct

Answer №1

Perhaps you just need to adjust the order slightly. Give this a try:

let container = {
  items: [] as string[]
};

Alternatively, consider utilizing an interface as suggested in another response.

Answer №2

One option is to create a custom type.

interface Container {
    items: number[];
}

const container: Container = { items: [] };

Alternatively, if the type is only used once, you can define it inline:

const container: { items: number[] } = { items: [] };

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

`When attempting to use Typescript with Electron, the error 'exports is not defined

Trying to launch my basic electron application, I utilize Typescript for development which then compiles into JavaScript. However, upon running the app, an error is encountered: ReferenceError: exports is not defined[Learn More] file:///Users/ahmet/Docume ...

Obtaining parameter types for functions from deeply nested types

I'm currently facing a challenge involving deeply nested parameters. When dealing with non-nested parameters, everything functions smoothly without any issues export type test = { 'fnc1': () => void, 'fnc2': () => void, ...

JavaScript onclick event on an image element

I have a JavaScript function that shows images using CSS styles. <script type="text/javascript"> $(function () { $("div[style]").click(function() { $("#full-wrap-new").css("background-image", $(this).css("background-image")); }); }); ...

Iterating through an array of MongoDB document IDs, querying each ID and then storing the results in a new array results in an empty array

Having trouble with the following code: const users = [] event.registeredUsers.forEach(userId => { User.findOne({ _id: userId }).then(user => { console.log(user) // displays a valid user users.push ...

Concealing or revealing an image with jQuery when hovering

I currently have 3 <a> tags within my html, each containing 2 images. Specifically, the greyscale images are the ones that are visible while the colored ones are set to display:none. I am aiming to achieve a functionality where upon hovering over th ...

Understanding the Parameters for discord.js Slash Commands

I am currently working on a calculation that involves using parameters input through a slash command. While entering the parameters works without any issues, I am facing difficulty in retrieving them. The current code is resulting in an error TypeError: ...

What is the best way to transform a JSON field containing nested arrays into a Java entity?

When working with a JSON obtained from the Twitter Stream API, I encountered a field containing a nested array that looks like this: { "bounding_box": { "coordinates": [ [ [ -74.026675, 40.683935 ], [ -74.026675, 40.8 ...

Tips on transmitting checkbox data from AJAX to PHP

I'm currently working with this code and facing an issue where data from checkboxes is being sent to PHP one by one. I want to be able to send multiple selected data at once. How can I modify the code to achieve this? $('#lunas').click(funct ...

Material appears abnormally shiny and reflective

I've been working on rendering an object with materials using Three.js, but I've noticed that the final result looks different from what I see in other online viewers, such as , which also utilizes Three.js under the hood. I've attempted to ...

Filter the angular accordion by passing a simple array value into the input

I am looking to filter my array of accordion items based on the value of the question matching the input I provide. I have tried using the filter method for this. this.accordionItems = [ { "topic":"polizze", " ...

access older siblings, accordion animation

I need assistance achieving an accordion effect on a DIV when hovering over it. The right side of the accordion is functioning properly, but I am facing issues with the left side. You can view my code on jsFiddle Could someone please provide guidance on ...

Using Javascript to create session-specific cookies

Is it possible to create session-only cookies using JavaScript that get removed when the browser is closed? Due to limitations, the website I am working on is HTML-only, so server-side scripts cannot be utilized. I came across a method mentioned here: b ...

Identifying periods of inactivity using an embedded iframe

I have developed a website that showcases a three.js model within an iframe. My goal is to redirect users back to the homepage (index.html) after they have been inactive for a specified amount of time. While I have managed to achieve this using JavaScript, ...

In React JS, the data from my response is not being saved into the variable

My goal is to store the response data in the variable activityType. Within the useEffect function, I am iterating over an API based on the tabs value. The API will return a boolean value of either true or false. While I can successfully log these values ...

I am currently working to resolve this particular wildcard issue with the help of TypeScript

I've been working on solving the wildcard problem with TypeScript, but I'm running into issues with some of the test cases I've created. Here's a brief overview of how the code operates: A balanced string is one where each character ap ...

Accordion Box glitch detected in Firefox browser

I have been working on a JavaScript function that controls a slide up/down box. However, I've encountered some issues with Firefox as the box only opens and closes once before failing to work properly again. Upon further investigation, it seems that F ...

Validating form field values in JavaScript prior to submission

My website features a search box that allows users to search through a database of books. When utilizing the search feature, users are presented with the following options: Search Query (a text input field) Where to search (a select field with the option ...

Rails not receiving JSON data

I am attempting a straightforward ajax call in Rails 4, but encountering issues with retrieving the json response. Below is the script I'm working with: $(document).on "submit", "form[name=upvote-form]", -> form = $(this) $.post "/vote", $(th ...

What is the best way to specifically target and style a component with CSS in a React application?

I'm facing a small issue with the React modals from Bootstrap in my application. In index.html, I include the following: <link rel="stylesheet" href="/assets/css/bootstrap.min.css"> <link rel="stylesheet" href=& ...

specifying a specific type in a declaration

In this scenario, my goal is to distinguish between different types when declaring a new type: type Schedule = { flag_active : boolean, } type Channel = { flag_archived : boolean } type CreateChangeLog = { from : null, to : Schedule | Channel } ty ...