In Typescript, default parameters can be inferred during type inference

Illustrative example of the concept I am attempting to implement:

const simpleExample = <T>(v: T = 'cat') => {
  return v;
};

Issue encountered:

Error message: Type 'string' is not assignable to type 'T'.
  'T' could be instantiated with a different type that may not relate to 'string'.ts(2322)

The inference process seems to function properly when default parameters are not used. Perhaps wrapping it in a construct that handles defaulting may solve this issue... It's perplexing why it fails in this scenario...




My specific implementation:

I aim for each Shape, Z, and Output to be deduced from the arguments provided, which works without issues if the default argument is excluded...

const createHooks = <
  Shape extends z.ZodRawShape,
  Z extends z.ZodObject<Shape, 'strict'>,
  Output extends z.ZodTypeAny
>(
  schema: Z,
  effect: (s: Z) => z.ZodEffects<Z, Output> = (s: Z) => s.transform((i) => i)
) => <Source, FProps extends { [k: string]: Record<string, any> }>({
  name,
  getInstanceKey,
  load,
  fieldProps,
}: {
  name: string;
  getInstanceKey: (s: Source) => string;
  load: (s: Source) => Z['_input'];
  fieldProps: FProps;
}) => {
 // ...
 return { }
}

Raised error:

'Output' could potentially have an unrelated type to '{ [k in keyof addQuestionMarks<{ [k in keyof Shape]: Shape[k]["_output"]; }>]: addQuestionMarks<{ [k in keyof Shape]: Shape[k]["_output"]; }>[k]; }'

This situation is frustrating as I expect any arbitrary type to trigger an error.

Answer №1

The issue arises when the function is called as simpleExample<number>(), where it should return a function of type (i: string) => number but fails to do so. One way to address this is by defining two overload signatures: one with a type parameter and another using the default argument without a type parameter.

function simpleExample<T>(f: (i: string) => T): (i: string) => T;
function simpleExample(): (i: string) => string;
function simpleExample(f = (i: string) => i) {
  return f;
};

Access the Playground Here

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 VSCode Debugger with Typescript: Traversing through Step Over/Into leads to JavaScript file路径

Just starting out with VSCode and using it to debug node.js code written in Typescript. One thing that's been bothering me is that when I stop at a breakpoint and try to "Step Over" or "Step Into", the debugger takes me to the compiled Javascript file ...

Calculate the sum of elements within an array

I've been attempting to calculate the sum of values in an array based on different levels, but so far I haven't had much success. Here are the data I'm working with (stored in a variable called totalByLevel): https://i.stack.imgur.com/rOP9 ...

What is the process of refactoring TypeScript and React project expressions?

Currently, I am utilizing TypeScript in a React project but encountering type errors. Please assist me by examining my code. I need help with refactoring this code. I believe the issue lies in the expression that uses the args of the useTabs function. ...

Initialize the routed component following the retrieval of data in the main component

In my simple Angular app, each routed component relies on data fetched from an API right after the application loads. I decided that the best approach is to initiate fetching in the root component, which also contains the router outlet. However, the activa ...

Retrieving information from an array using a variable results in undefined, but using a specific number returns the desired object

Currently, in the process of learning TypeScript as my second language, I am encountering some challenges with arrays. I have observed peculiar behavior when accessing the list with a variable as opposed to a hardcoded number. The code snippet in questi ...

Karma Jasmin is puzzled as to why her tests are failing intermittently, despite the absence of any actual test cases

In this snippet, you will find my oninit method which I am instructed not to modify. ngOnInit(): void { this.setCustomizedValues(); this.sub = PubSub.subscribe('highlightEntity', (subId, entityIdentifier: string) => { ...

Reinstalling node does not remove Typescript, as it remains intact even after the

When I was working on my Angular 5 project, I encountered the following error during compilation: @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="31525e5c41585d54431c525d5871041f031f0000">[email protected]</ ...

Converting JSON Arrays into Typescript Arrays

I am working with a JSON file that contains an array object like this: [ { "VergiNo": "XXXXXXX" }, { "VergiNo": "YYYYYY" }, { "VergiNo": "ZZZZZZ" } ] After importing this JSON file into my Typescript file, import * as companies f ...

What distinguishes between the methods of detecting falsy and truthy values?

While working with JavaScript / Typescript, I often find myself needing to verify if a length exists or if a value is true or false. So, the main query arises: are there any differences in performance or behavior when checking like this... const data = [ ...

What are the steps to globalize the ng-bootstrap datepicker?

For my current project, I am utilizing the ng-bootstrap datePicker component. The demo for my simple datePicker widget can be found here. However, I am now seeking to internationalize it by setting it to use the Russian language. Any assistance with this ...

WebStorm is not auto-completing the Emotion Styled Components

While using @emotion/styled in WebStorm, I have noticed that there is no Intellisense for autocomplete within my style object. However, Typescript does seem to be checking to some extent: const StepTimer = styled.button({ borderRadius: 50, height: &ap ...

The transition from an unknown type to a known type occurs through type inference when a method is

In my current project, I have a class with a single generic parameter T. The challenge arises when this class is sometimes constructed with a known value for T, and other times without a value, leaving T in an unknown state. It becomes cumbersome to always ...

Issue occurred while trying to deploy Firebase functions following GTS initialization

Objective: I am aiming to integrate Google's TypeScript style guide, gts, into my Firebase Functions project. Desired Outcome: I expect that executing the command firebase deploy --only functions will successfully deploy my functions even after init ...

The URL is reverted back to the previous address

Currently in the process of developing an Angular application, I've encountered a minor visual issue. On one of the pages, there is a ReactiveForm implemented, but whenever I navigate to that page, the URL reverts back to the previous one (even though ...

Javascript Library Issue: "Implicitly Declared Type 'Any' Error"

I am currently in the process of developing a JavaScript library that will interact with an API. My goal is to create a module that can be easily published on npm and utilized across various frameworks such as Angular or React. Below is the code snippet fo ...

I am looking to remove the drop down icon if there are no child data present in Angular 4

Is there a way to dynamically show or hide the drop-down icon depending on whether there is child data present in Angular 4? I am using rowGroup: true to group parent and child elements together. I need the drop-down icon to be hidden when there are no ch ...

Is it possible to access the type definitions for the newer versions 4.0 and above of AgGrid?

Currently, I am utilizing "ag-grid": "4.0.5" in a project that involves Angular 1.5.2 and Typescript within Visual Studio 2015. When trying to install the type definitions through tsd using the command tsd install ag-grid --resolve --save, it installs an ...

Why isn't useEffect recognizing the variable change?

Within my project, I am working with three key files: Date Component Preview Page (used to display the date component) useDateController (hook responsible for managing all things date related) In each of these files, I have included the following code sn ...

NextJS's tree shaking feature indiscriminately includes all modules from node_modules, irrespective of whether they are actually used or

Looking at the screenshot of my Next JS package size, I noticed that the react-color components from node_modules are bloating the bundle with unnecessary files like photoshop.js, sketch.js, etc. I'm currently importing them this way: import { Github ...

Ways to effectively leverage the types from lib.d.ts?

It appears that the issue at hand is related to WebStorm IDE. I have reported it to WebStorm and you can track the progress here. Currently, I am working with Angular 2 and TypeScript 2. I am wondering how to explicitly utilize the location from lib.d.ts ...