Tips for verifying that parameters possess designated characteristics in TypeScript

How can I ensure that data2 and data3 work correctly, while data1 triggers an error if the data type is not specified as shown in the code below?

I need to validate that when a user enters params like {name: 'aa', age: 20}, it should throw an error because the parameters must include a data type date (with any key name) like

{name: 'aa', age: 20, born: new Date('10-10-2020')

const data1 = {
  name: 'Lorem',
  age: 12
}

const data2 = {
  name: 'Lorem',
  age: 12,
  born: new Date('10/10/1990')
}

const data3 = {
  name: 'epsum',
  age: 12,
  died: new Date('10/10/1990')
}

interface PropsA {
  name: string;
  age: number;
}

const test = (inputParams: PropsA & { [x: string]: Date }) => {
  return inputParams
}

test(data1) // It should result in an error since it lacks a value with data type Date apart from age and name

// How can I correct this error and make it work?
test(data2)
test(data3)

Playground

Answer №1

Utilizing a generic utility type to validate the specified type:

type HasDate<T> = Date extends T[keyof T] ? T : never;

const verify = <T extends PropsA>(inputParams: HasDate<T>) => {
  return inputParams;
};

TypeScript will intelligently deduce T using HasDate.

verify(data1) // ! errors
verify(data2) // ok
verify(data3) // ok

Playground


Your approach is unsuccessful as { [x: string]: Date } requires all keys to have Date values, which does not apply to PropA, causing data2 and data3 to fail.

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

Invalid sequencing of Nest.js async onModuleInit causing issues

I am dealing with a scenario where ServiceA relies on RedisService. In order for ServiceA to be fully operational, it must wait for RedisService to complete its initialization process (specifically, for RedisService.onModuleInit to be called and awaited). ...

What are the reasons for encountering errors when using concat to merge two arrays of objects?

Hello, I am encountering an Error The error message says "concat is not a function" Here is what I am attempting searchResults:any; // inside class export results:any this.candidateSearch.postSearch(this.searchedInput,"candidateSearch"). ...

Guidelines on incorporating emotion/styled into React applications with TypeScript

Including my root component in the ThemeProvider from @emotion/react has granted me access to props.theme. Here is an example: const StyledDiv = styled.div` background-color: ${(props) => props.theme.palette.primary.main}; `; Issue: TypeScript indica ...

Instructions on how to implement a readmore button for texts that exceed a specific character length

I am attempting to display a "Read more" button if the length of a comment exceeds 80 characters. This is how I am checking it: <tr repeat.for="m of comments"> <td if.bind="showLess">${m.comment.length < 80 ? m.comment : ...

An issue arises with launching karma.js when importing node-openid-client in a TypeScript specification file

Utilizing the node-openid-client library for OpenIDConnect based authentication with an OpenID Provider. Encountering challenges while attempting to write test cases for the program. The application runs smoothly from node CLI, obtaining the code and toke ...

Expanding a TypeScript type by creating an alias for a property

I am working on defining a type that allows its properties to be "aliased" with another name. type TTitle: string; type Data<SomethingHere> = { id: string, title: TTitle, owner: TPerson, } type ExtendedData = Data<{cardTitle: "title&qu ...

Incorporating Imported Modules into the Final Build of a Typescript Project

In my Visual Studio Code Typescript project, I have set up some basic configurations and used npm to download libraries. One of the main files in my project is main.ts which includes the following code: import ApexCharts from 'apexcharts' var c ...

Function in nodejs throwing an error: Return type missing

I am facing an issue with this code snippet while trying to compile the application. public async test(options?: { engine?: Config }): Promise<any> { const hostel = new Service({ list: this.servicesList, createService ...

Definition files (.d.ts) for JavaScript modules

I'm currently working on creating Typescript typings for the link2aws package in order to incorporate it into my Angular project. Despite generating a .d.ts file, I am still encountering the following error message: TypeError: (new link2aws__WEBPACK_I ...

Where is the best location to store types/interfaces so that they can be accessed globally throughout the codebase?

I often find myself wondering about the best place to store types and interfaces related to a specific class in TypeScript. There are numerous of them used throughout the code base, and I would rather not constantly import them but have them available gl ...

Error: Unable to inject HttpClient dependency. Angular 5

I recently switched to using the Angular template in Visual Studio 2017 and decided to update to Angular 5.2. However, I encountered an error while trying to make a http call from the service class. The error message I received is: Here is the code snipp ...

How can I retrieve List<T> from a Razor Page using TypeScript?

Within my ViewModel, I have an Items collection: public class ItemViewModel{ public List<Item> Items {get;set;} } In the Index.cshtml file: @if(Model.Items != null){ <li><a id="item-id-link" href="#" data-items="@Model.Items"> ...

Error when running end-to-end tests in Angular CLI using the ng e2e

Recently, I created a new Angular 4 project using the Angular CLI. Upon running ng e2e, the sample end-to-end test worked flawlessly. However, when I later added a subfolder named services in the app folder and generated a service within it, the ng e2e com ...

Ways to retrieve the most recent update of a specialized typing software

When attempting to run typings install in a sample project with the below typings.js file, I received a warning. How can we determine the latest version number and what does the number after the + symbol signify? { "globalDependencies": { "core-js ...

Form with Material-UI's FreeSolo AutoComplete feature

Visit this Sandbox for more details In the provided SandBox example, Material AutoComplete is being used as a multiple input with free options. The component is expected to return ["term1","term2","term3"] to Formik, and each string should be displayed as ...

Can you explain the distinction between declaring type using the colon versus the as syntax?

Can you explain the variation between using the : syntax for declaring type let serverMessage: UServerMessage = message; and the as syntax? let serverMessage = message as UServerMessage; It appears that they yield identical outcomes in this particular ...

Exploring the functionality of CanDeactiveGuard and ModalDialogService through unit testing

In my application, the CanDeactiveGuard is functioning properly. During unit testing, I encountered an issue with one test where I intended to use callThrough to invoke the openConfirmDialog() method within the Guard. This method triggers the Modal Dialog ...

Refresh Angular 2 data after a related data update

I am facing an issue with my <select> elements in Angular. One for the Districts and another for the Cities. The districts are fetched using the getDistricts() function within the ngOnInit() function without any problems. However, I am unsure how to ...

When attempting to utilize yarn link, I receive an error message indicating that the other folder is not recognized as a module

After successfully running "yarn link," I encountered an issue when attempting to use it in a different project. The error message displayed was ../../.tsx is not a module. What could be causing this problem? const App: React.FC = () => { const [op ...

typescript - add a global library import statement to every script

Recently, I began working on a TypeScript project in Node.js. I am looking to add import 'source-map-support/register'; to all of my .ts files for better visibility of TS source in stack traces. Is there a method to implement this without manuall ...