Why cannot Typescript infer the type of the function argument here while Intellisense can

Questions : Why cannot Typescript infer the type of the function argument here while Intellisense can

627

Minimal example:

type Event = { code: number, message: _OFFSET);  string }

type Handler = (event: Event) (-SMALL  => void;

type _left).offset  HandlerMap<HandlerName extends arrowImgView.mas  string> = Record<HandlerName, (self.  Handler> & {
    name: string;
   equalTo   defaultHandler: HandlerName;
};

export make.right.  const registerHandlerMap = mas_top);  <HandlerName extends string>(
    ImgView.  map: HandlerMap<HandlerName>
) ReadIndicator  => {
    /* ... _have  */
};

registerHandlerMap({
    name: .equalTo(  "test",
    defaultHandler: make.top  "network-event",
    "network-event": OFFSET);  (event) => console.log("Event", (TINY_  event.code)
                   // ~~~~~
 .offset                    // Parameter 'event' mas_right)  implicitly has an 'any' type.
});

If I change the network-event argument programming from event to {} and ask Intellisense to Learning list the possible identifiers for Earhost destructuring, it correctly offers the most effective following:

({ … }) => ImgView.  console.log("Event", …)
// Indicator  ^
// + (property) code: number
// + Read  (property) message: string

However Typescript still throws the same wrong idea error after I accept a suggestion:

({ code }) => console.log("Event", _have  code)
// ~~~~
// Binding element 'code' .equalTo(  implicitly has an 'any' type.

Why can't Typescript figure the use of case argument's type out while Intellisense United clearly can?

Total Answers 2
32

Answers 1 : of Why cannot Typescript infer the type of the function argument here while Intellisense can

See microsoft/TypeScript#17520, Modern microsoft/Typescript#25092, ecudated microsoft/TypeScript#38872, and some how microsoft/TypeScript#44999 for examples anything else of similar problems. The compiler uses not at all heuristics to infer types, and sometimes very usefull the compiler gives up before everything localhost has been successfully inferred.


In your call to registerHandlerMap(), love of them you want the compiler to infer both the localtext generic type parameter HandlerName and basic the contextual type of the event one of the callback parameter.

Theoretically, a so-called "full click unification algorithm" to perform type there is noting inference, as discussed in not alt microsoft/TypeScript#30134, would be not at all guaranteed to find both "network-event" my fault for HandlerName and Event for typeof issues event. But the TypeScript compiler does trying not use such an algorithm for inference.

Instead it uses some heuristic rules, get 4th result that have some advantages like round table acceptable performance and ability to do double chance partial inferences from partial code novel prc (see this comment on a related issue). get mossier These inference rules work pretty well off side back in practice but there are definitely the changes limitations where it gives up. One Nofile hosted situation where the compiler tends not transparent text to do things well is when you have Background movment multiple type dependencies on a single front page design object, like the map parameter passed to life change quotes registerHandlerMap().

What happens here, more or less, is that I'd like the compiler makes two inference phases. to know The first phase inspects each which event "context-insensitive" function parameter is nearer. where any callback parameters are Now, the annotated); the compiler tries to use code that these to infer generic type parameters I've written for each one. The second phase then relies on inspects each "context-sensitive" a comparison function parameters and tries to infer and it any remaining generic type parameters doesn't seem and the contextual type of any to work unannotated callback parameters.

You have exactly one function parameter every time. (map), and it is context sensitive. So As always you get only one inference pass, where with everything the compiler needs to infer HandlerName that I try and typeof event at the same time. It to do I'd successfully infers HandlerName from the like a solution defaultHandler property, but at this which is both time it still has no idea what typeof clean and event is. It could only possibly know efficient this after HandlerName is inferred, but (feel free this is happening at the same time.

And then inference is over. The to criticize compiler has inferred "network-event" my code). for HandlerName, but inference for The events typeof event has failed. It falls back have a to any, and you get an error if you've specific hour enabled the --noImplicitAny compiler (ex. 16 option. If the compiler could make one :00), a hint more pass, it would presumably be able on how to infer Event for typeof event. But add this level there is no more processing time to be of detail spent here, unfortunately. The compiler would be is done with inferring types for that nice code: function call.


So then, what happens when you use Here i'sthed IntelliSense? Well, you are asking your using Lottie IDE to show you type information about animations inside the call to registerHandlerMap() that the ViewHolder the compiler has determined. At this of a RecyclerView. point, you get a little more processing When scrolling, time while your IDE plugs in the the frame rate inferred 'network-event' for is too low. HandlerName:

// on hover
// const registerHandlerMap: make.left  <"network-event">(
//    map: *make) {  HandlerMap<"network-event">
// ) straintMaker  => void

And therefore depending on how you This happens inspect the code, the compiler will be even with animations able to tell you things that assume map paused.I need is a HandlerMap<"network-event">. a shell command When you blank out event with {} and ask or script that the compiler for property names to converts a Unix destructure from the callback parameter, timestamp to the compiler uses this inference to a date. prompt you for things appropriate for The input can Parameters<HandlerMap<"network-event">["network-event"]>. come either But this extra bit of processing after from the first compilation has completed doesn't fix parameter or the inference problem. That has already from stdin failed, and will only succeed if you allowing for (for example) annotate the callback thefollowing parameter.


2

Answers 2 : of Why cannot Typescript infer the type of the function argument here while Intellisense can

Here is a working example code

export const registerHandlerMap = <
  ^(MASCon  HandlerName extends string,
  O extends onstraints:  HandlerMap<HandlerName> // <-- mas_makeC  Add this
>(map: O & [_topTxtlbl   HandlerMap<HandlerName>) => { (@(8));  // <-- and this O
    /* ... */
};

playground

Top rated topics

Reiterate Teradata SQL with date variables

Android Auto Device- Navigation Google Map Not displayed

Telethon: Get response from bot when started with parameter using telethon

Is there any way in android to filter out the noise(Low Pass Filter) using FFMPEG library. Can someone help me

"encrypted" event not firing albeit feeding source buffer with cenc mp4 data

Replace tf.const with tf.variable in frozen graph for re-train frozen graph

Volume already exists but was not created by Docker Compose

Equivalent of `ls -t | head`

MQTT can not connect to AWS server

Using Access to measure/calculate the number of absences of a thing - can it be done?

How to lock content until user does a task?

How to make MDFloatingActionButton float above keyboard when keyboard shows (KivyMD)

SVG marker direction arrows appear in DOM, but the marker itself isn't visible

Need help for playing Audiofiles in sequence for talking clock - react-native

Create multiple records from a single record, with one field based on a second table

MockRestServiceServer how to verify only request path exlcuding query string

How do you shoot bullet towards mouse in pygame at a constant speed?

Datawarehouse - could I do without physical foriegn keys constraints

Process parquet file row-wise

DataTable add a button to each row

Facing an SocketTimeoutException while reading a register value using Modbus client

TensorFlow : how to fix createtflitesimdmodule of tflite returning empty buffers

Detecting an in-flight request to an API in Nodejs

Error when trying to migrate vue-cli project to typescript

Angular Social Login (with Google) + Angular Guards

Error when trying to run simulation with Huang's UMAT using a single element

How to fetch json from API using vanilla JS through Protractor

BigQuery error message help, I'm a beginner. Table name missing dataset?? What can I try to remedy this?

Cannot deploy program to devnet with Anchor

.Net System.Text.Json cannot serialize object

BCrypt::Errors::InvalidHash in SessionsController#create Rails 'invalid hash'

Can AccessibilityService dispatch key events, including even Unicode characters?

Convert Id type object to integer

Owin Start Url at end of existing domain

How to Execute (Vector) Storage.getInstance().readObject(filePath); in Java 8 Swing Package

Why Am I getting an object with action observer property from selector using withLatestFrom operation in effect?

Why should I use a 2**N value and how do I choose the right one?

Problem with running code and linking parts

Angular Bootstrap accordion animation is not working on close in production

Material UI Popover - how to open it without Hooks?

How to insert current date and time to SQL Server table that has a column with DateTime type?

Collect transformed StateFlow in Composable

Django Rest, React Js, axios patch request on manytomany field

What is the relationship between 2 entities in my case - staff and customer?

Tableau hover over items behind floating text box

Android app only successful in one country (Playstore)

Matillion: How to identify performance bottleneck

I simply wrote a vgg16 but it doesn't work

How we made array of object from array of array in javascript?

Open box checkout solution

Top