const obj: {[key: string]: string} = {foo: 'x', bar: 'y'};
type ObjType = keyof typeof obj;
Is there a way to restrict ObjType
to only accept values "foo" or "bar" without changing the type of obj
?
const obj: {[key: string]: string} = {foo: 'x', bar: 'y'};
type ObjType = keyof typeof obj;
Is there a way to restrict ObjType
to only accept values "foo" or "bar" without changing the type of obj
?
It is currently not possible to achieve this in typescript 4.8. You are unable to restrict a type and then use a more specific version of that type in the same assignment.
The common workaround is to utilize a generic function, although it is not ideal.
function createObject<T extends { [key: string]: string }>(obj: T) {
return obj
}
const newObj = createObject({foo: 'x', bar: 'y'})
type NewObjType = keyof typeof newObj // 'foo' | 'bar'
However, it appears that the upcoming version of typescript (4.9) may introduce the satisfies
operator. More information can be found on this github issue
This new feature will allow you to enforce a constraint and infer the more specific type simultaneously.
const newObj = {foo: 'x', bar: 'y'} satisfies { [key: string]: string }
type NewObjType = keyof typeof newObj // 'foo' | 'bar'
Regardless, changes to how newObj
is declared will be necessary for any of these approaches to work.
Allow the inference to handle it:
const object = {name: 'Alice', age: 30};
type ObjectType = keyof typeof object; // "name" | "age"
Looking for assistance with the code snippet below: const compress = require('compression'); export const handleCompression = compress({ filter: function (req: express.Request, res: express.Response) { return (/json|text|javascript|css|fo ...
I am working with a function called getStaticProps in Next.js that returns a Promise, resolving to an Object with the following structure: type StaticProps<P> = { props: P; revalidate?: number | boolean; } To generically "unwrap" the type o ...
Trying to find a solution for implementing TSDocs with a string literal type declaration in TypeScript. For instance: type InputType = /** Comment should also appear for num1 */ 'num1' | /** Would like the TSDoc to be visible for num2 as well ...
Is there a way to dynamically format input as USD currency while typing? The input should have 2 decimal places and populate from right to left. For example, if I type 54.60 it should display as $0.05 -> $0.54 -> $5.46 -> $54.60. I found this PLUN ...
Working on my first project using NextJS, I'm curious about the proper approach to managing dynamic routing. I've set up a http://localhost:3000/trips route that shows a page with a list of cards representing different "trips": https://i.stack. ...
Currently, I am in the process of organizing my logframe and need to arrange my array as follows: Impact Outcomes Output Activities Here is the initial configuration of my array: { id: 15, parentId: 18, type: OUTPUT, sequence: 1 }, { id: 16, parentId: ...
Within the server environment, I have defined the enum and query in the schema: type Query { hello: String! getData(dataType: DataType!): [DataPoint] } enum DataType { ACCOUNT, USER, COMPANY } ... Now, on the client s ...
My intention was simply to update a property within an object inside an array and then update the state of the array. However, I encountered an issue where all properties except the one that was updated became undefined. The code in question is as follows ...
As a newcomer to TypeScript, I am in search of an elegant solution for the following dilemma. I have a state variable named emailAddress, which is assigned a value from an input field. Additionally, I need the input field to display and update its value ba ...
How does the compiler resolve the $ in the code snippet below, even without importing jQuery? function f () { $('#loadFiles').click() // ok $$('#loadFiles').click() // error, can't find name '$$' } The compile ...
Working on a front-end application utilizing React, Typescript, Effector, FetchAPI, and other technologies. Created an Effector effect to delete an item in the backend: export const deleteItemFX = createEffect({ handler: (id: string) => { return ...
I am in the process of creating an Angular application that enables two users to have a video call using the Openvidu calling solution. As part of this application, I have implemented a feature that allows users to switch between different cameras or micr ...
Currently, I'm engaged in a React project that utilizes TypeScript. Within the project, there is an integration of the react-select component into another customized component. The custom wrapped component code is as follows: import * as React from " ...
I need help with the following code snippet: const fff = async (req: express.Request, res: express.Response): Promise<void> => {...} How can I specify that req.body.xxx exists? I want it to be recognized when I reference req.body.xxx as a propert ...
I am in the process of updating a current Angular application that uses AMD with TypeScript 1.5 ES6 module syntax. Our modules are currently stored in separate files, and the main "app" module is defined like this... define('app', ['angular ...
While working on my Angular 1 app in typescript, I faced an issue when importing angular using the following syntax: import * as angular from 'angular'; Instead of importing angular from angular, it was being imported from angular-mocks. Thi ...
I am currently utilizing Typescript and Angular 4 in my work. Within my project, I have two lists implemented using rxjs/Rx. ... myList: Observable<MyClass[]>; filteredList: Observable<MyClass[]>; ... My objective is to filter the myList base ...
My project involves utilizing multiple classes that represent entities from a database. abstract class Entity { static columns: Column[]; static showInNav: boolean; static dependencies: string[]; // non-static fields } class Entity_A exten ...
I have created my own typescript library using the typescript-starter tool found at . Here is how I structured the types folder: https://i.stack.imgur.com/igAuj.png After installing this package, I attempted a function or service call as depicted in the ...
Having an issue while trying to integrate @angular/pwa, it keeps showing me an error saying "Bootstrap call not found". It's worth mentioning that I have removed app.module.ts and am using standalone components in various places without any module. Cu ...