问:
Missing data points while writing from a file using cURL in InfluxDB
I was trying to insert data into an InfluxDB database as per this documentation by executing the command curl -i -XPOST 'http://localhost:8086/write?db=myDB' --data-binary @data.txt. Where data.txt is a file containing more than 50 points.

Output:

```<code>HTTP/1.1 100 Continue

HTTP/1.1 204 No Content
Content-Type: application/json
Request-Id: 93487c9c-a1a8-11ea-80bd-9829a645199e
X-Influxdb-Build: OSS
X-Influxdb-Version: 1.8.0
X-Request-Id: 93487c9c-a1a8-11ea-80bd-9829a645199e
Date: Fri, 29 May 2020 12:33:18 GMT
</code>```

I was only able to write 50 points to myDB and I thought it was due to HTTP/1.1 100 Continue. After some googling, I landed on this article and as per that I modified and executed the above command like curl -H 'Expect:' -i -XPOST 'http://localhost:8086/write?db=myDB' --data-binary @data.txt

Output:

```<code>HTTP/1.1 204 No Content
Content-Type: application/json
Request-Id: 54b34ebd-a1bc-11ea-80ca-9829a645199e
X-Influxdb-Build: OSS
X-Influxdb-Version: 1.8.0
X-Request-Id: 54b34ebd-a1bc-11ea-80ca-9829a645199e
Date: Fri, 29 May 2020 14:54:43 GMT
</code>```

I was successfully able to bypass HTTP/1.1 100 Continue but still, I am only writing 50 points to myDB.

I am an absolute NOOB to InfluxDB and cURL

答:
Recently I figured out the issue. The problem is with the contents of data.txt file. I am writing each data point without a timestamp and because of that all the measurents was allotted with the same timestamp.

E.g.,

```<code>temperature,tag=computer node="cpu",value=38
temperature,tag=computer node="gpu",value=45
temperature,tag=computer node="ram",value=40
</code>```

If I had the above three measurements in file data.txt without timestamp the InfluxDB will only accept the final value (overwrites previous values since all are having same timestamp).

Since I am NOOB to this, I wasn't aware of all the properties of InfluxDB.

Body:
I was trying to insert data into an InfluxDB database as per this documentation by executing the command curl -i -XPOST 'http://localhost:8086/write?db=myDB' --data-binary @data.txt. Where data.txt is a file containing more than 50 points.

Output:

HTTP/1.1 100 Continue

HTTP/1.1 204 No Content
Content-Type: application/json
Request-Id: 93487c9c-a1a8-11ea-80bd-9829a645199e
X-Influxdb-Build: OSS
X-Influxdb-Version: 1.8.0
X-Request-Id: 93487c9c-a1a8-11ea-80bd-9829a645199e
Date: Fri, 29 May 2020 12:33:18 GMT

I was only able to write 50 points to myDB and I thought it was due to HTTP/1.1 100 Continue. After some googling, I landed on this article and as per that I modified and executed the above command like curl -H 'Expect:' -i -XPOST 'http://localhost:8086/write?db=myDB' --data-binary @data.txt

Output:

HTTP/1.1 204 No Content
Content-Type: application/json
Request-Id: 54b34ebd-a1bc-11ea-80ca-9829a645199e
X-Influxdb-Build: OSS
X-Influxdb-Version: 1.8.0
X-Request-Id: 54b34ebd-a1bc-11ea-80ca-9829a645199e
Date: Fri, 29 May 2020 14:54:43 GMT

I was successfully able to bypass HTTP/1.1 100 Continue but still, I am only writing 50 points to myDB.

I am an absolute NOOB to InfluxDB and cURL

Body:
Recently I figured out the issue. The problem is with the contents of data.txt file. I am writing each data point without a timestamp and because of that all the measurents was allotted with the same timestamp.

E.g.,

temperature,tag=computer node="cpu",value=38
temperature,tag=computer node="gpu",value=45
temperature,tag=computer node="ram",value=40

If I had the above three measurements in file data.txt without timestamp the InfluxDB will only accept the final value (overwrites previous values since all are having same timestamp).

Since I am NOOB to this, I wasn't aware of all the properties of InfluxDB.


来源: stackexchange

问:
Activity not opening when clicking menu item
I am trying to tap on the "logout" option whose id is logout but nothing happens. Below is my code

```<code>@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.requestpayment,menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()){
        case R.id.logout:
            Intent intent=new Intent(this,Logout.class);
            this.startActivity(intent);
            break;
    }
    return super.onOptionsItemSelected(item);
}
</code>```

please help

答:
in onCreateOptionsMenu method replace

```<code>return super.onCreateOptionsMenu(menu);
</code>```

by

```<code>return true;
</code>```

and replace super.onOptionsItemSelected(item); in onOptionsItemSelected() by return true

ContentLicense: CC BY-SA 4.0

Body:
I am trying to tap on the "logout" option whose id is logout but nothing happens. Below is my code

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.requestpayment,menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()){
        case R.id.logout:
            Intent intent=new Intent(this,Logout.class);
            this.startActivity(intent);
            break;
    }
    return super.onOptionsItemSelected(item);
}

please help

Body:
in onCreateOptionsMenu method replace

return super.onCreateOptionsMenu(menu);

by

return true;

and replace super.onOptionsItemSelected(item); in onOptionsItemSelected() by return true


问:
Step Definition detection only works when project is configured as cucumber project.- Virtual Machine
feature file and stepdefiniton file could not be connected.  It happens only in eclipse installed in Win Server 2012R2 Virtual Machine.</p>

答:
This error will appear when you import any new cucumber project from git or directly from local system. Because you have not configured the project to cucumber and it is configured only to maven.

This error can appear for both Selenium and appium testing for web and mobile automation testing.

You can use below screenshot to convert to cucumber project.


问:
how to implement csrf without csrf token in django
In django, if I want to use csrf token, I need to imbed a form with csrf token in django template. However as a backend-engineer I am co-working with a front-end engineer whose code is not available for me. So I caanot use the template. In this case, if I want still the csrf function. what should I do?</p>

答:
You may use @csrf_exempt decorator to except csrf tokens.

First, import decorator

```<code>from django.views.decorators.csrf import csrf_exempt
</code>```

Then add @csrf_exempt before your view.

```<code>@csrf_exempt
def my_view(request):
return HttpResponse('Hello world')
</code>```

More details can be found here enter link description here

Body:
You may use @csrf_exempt decorator to except csrf tokens.

First, import decorator

from django.views.decorators.csrf import csrf_exempt

Then add @csrf_exempt before your view.

@csrf_exempt
def my_view(request):
return HttpResponse('Hello world')

More details can be found here enter link description here


问:
Running python from a mounted filesystem
I have a django-based application that I'm running from a virtualbox-shared folder. When starting using 'runserver' I get an error indicating that a module could not be found. After copying the same exact code to a directory on the local filesystem, it starts and runs as expected.

Anyone seen anything like this when working with virtualbox and python?

It appears that module resolution is working differently when python is run from the mounted shared folder vs. the local folder, but I can't find a smoking gun that indicates whether or not it's caused by how that folder is mounted or python.

Thanks!

答: One solution I found was to mount my shared folder with cifs into the VM. That seems to work flawlessly. I did not found a solution for the vboxsf.</p>

ContentLicense: CC BY-SA 3.0


问:
How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?
Sometimes when I'm editing page or control the .designer files stop being updated with the new controls I'm putting on the page.  I'm not sure what's causing this to happen, but I'm wondering if there's any way of forcing Visual Studio to regenerate the .designer file.  I'm using Visual Studio 2008

EDIT: Sorry I should have noted I've already tried:

Closing & re-opening all the files & Visual Studio

Making a change to a runat="server" control on the page

Deleting & re-adding the page directive

答:
If you are like me and you add old .ASPX files to a more recent project.
You are probably going to forget some of the controls used on the page.

If so, first thing, if there are multiple files you are installing;
Fix one at a time first.

When you compile, fix errors generated. They will probably be the same
errors in all the files.

Next, if you have Designer files, delete all of the inserted - designer files.
Next, make sure there are not any other errors when you compile, other than
the designer files.

Finally right click your web project and click on Convert to Web Application.
This will insert the designer files you need.

These are the absolute best steps to fix the issues.

OwnerDisplayName: Glenn Slaven

ContentLicense: CC BY-SA 2.5


问:
Laravel 5.1: keep uploaded file as old input
I'm using a form in Laravel 5.1 to post some text and to upload a file. It looks like this (simplified version):

```<code>{!! Form::open(array('url' => 'foo/bar')) !!}
    {!! Form::text('image_name') !!}
    {!! Form::file('image') !!}
    {!! Form::submit('Submit!') !!}
{!! Form::close() !!}
</code>```

The textfield is required, so I added a $validator in my controller. If validation fails, the user is redirected back to the form. I use the withInput() method to repopulate the form so that the user doesn't have to fill it in again:

```<code>if ($validator->fails()) {
    return redirect()->back()->withInput();
}
</code>```

This will get the old input back for textfields, dropdowns etc. But if the user has uploaded a file, the file selection is gone when validation fails and has to be selected again. Is there any way in Laravel to remember file selection as old input?

Thanks!

答:
If your file is an image, you can create a hidden input and write there base64 string there when the user uploads the image

```<code>{!! Form::open(array('url' => 'foo/bar')) !!}
{!! Form::text('image_name') !!}
{!! Form::hidden('base64_image') !!}
{!! Form::file('image') !!}
{!! Form::submit('Submit!') !!}
{!! Form::close() !!}
</code>```

Body:
I'm using a form in Laravel 5.1 to post some text and to upload a file. It looks like this (simplified version):

{!! Form::open(array('url' => 'foo/bar')) !!}
    {!! Form::text('image_name') !!}
    {!! Form::file('image') !!}
    {!! Form::submit('Submit!') !!}
{!! Form::close() !!}

The textfield is required, so I added a $validator in my controller. If validation fails, the user is redirected back to the form. I use the withInput() method to repopulate the form so that the user doesn't have to fill it in again:

if ($validator->fails()) {
    return redirect()->back()->withInput();
}

This will get the old input back for textfields, dropdowns etc. But if the user has uploaded a file, the file selection is gone when validation fails and has to be selected again. Is there any way in Laravel to remember file selection as old input?

Thanks!

Body:
If your file is an image, you can create a hidden input and write there base64 string there when the user uploads the image

{!! Form::open(array('url' => 'foo/bar')) !!}
{!! Form::text('image_name') !!}
{!! Form::hidden('base64_image') !!}
{!! Form::file('image') !!}
{!! Form::submit('Submit!') !!}
{!! Form::close() !!}


问:
XSD: A <xs:choice> equivalent for attributes
I wish to create an XML document in which one of its elements must be defined with one of two known attributes, but not both.

For example, I would like to define a "webAddress" element as follows:

```<code> <xs:element name="webAddress">
     <xs:complexType>
         <xs:attribute name="hostName" type="xs:string"/>
         <xs:attribute name="hostAddress" type="xs:string"/>
     </xs:complexType>
 </xs:element>
</code>```

but I only want a user to be able to define either a hostName attribute (e.g., hostName= ") or a hostAddress (e.g., hostAddress="") attribute, but not both.  It appears that the  construct accomplishes this for elements.  Is there a functional equivalent for attributes, or is there a better way to approach this?

If found that we can't do this with W3C XML Schema.
We can use an embedded schematron rule but can we do it on choice element by checking element and attribute together?
For example something like this:

```<code><xs:choice>
     <xs:element name="webAddress">
         <xs:complexType>
             <xs:attribute name="hostName" type="xs:string"/>
         </xs:complexType>
     </xs:element>
     <xs:element name="webAddress">
         <xs:complexType>
             <xs:attribute name="hostAddress" type="xs:string"/>
         </xs:complexType>
     </xs:element>
  </xs:choice>
</code>```

答:
You can achieve this with a XSD key:</p>

```<code><xs:element name="webAddress">
    <xs:complexType>
        <xs:attribute name="hostName" type="xs:string" use="optional" />
        <xs:attribute name="hostAddress" type="xs:string" use="optional" />
    </xs:complexType>

    <!-- Validate either name or address attribute specified (but not both). -->
    <xs:key name="WebAddressHostNameOrAddressAttributePresent">
        <xs:selector xpath="." />
        <xs:field xpath="@hostName | @hostAddress" />
    </xs:key>
</xs:element>
</code>```

Body:
I wish to create an XML document in which one of its elements must be defined with one of two known attributes, but not both.

For example, I would like to define a "webAddress" element as follows:

 <xs:element name="webAddress">
     <xs:complexType>
         <xs:attribute name="hostName" type="xs:string"/>
         <xs:attribute name="hostAddress" type="xs:string"/>
     </xs:complexType>
 </xs:element>

but I only want a user to be able to define either a hostName attribute (e.g., hostName= ") or a hostAddress (e.g., hostAddress="") attribute, but not both.  It appears that the  construct accomplishes this for elements.  Is there a functional equivalent for attributes, or is there a better way to approach this?

If found that we can't do this with W3C XML Schema.
We can use an embedded schematron rule but can we do it on choice element by checking element and attribute together?
For example something like this:

<xs:choice>
     <xs:element name="webAddress">
         <xs:complexType>
             <xs:attribute name="hostName" type="xs:string"/>
         </xs:complexType>
     </xs:element>
     <xs:element name="webAddress">
         <xs:complexType>
             <xs:attribute name="hostAddress" type="xs:string"/>
         </xs:complexType>
     </xs:element>
  </xs:choice>

Body:
You can achieve this with a XSD key:

<xs:element name="webAddress">
    <xs:complexType>
        <xs:attribute name="hostName" type="xs:string" use="optional" />
        <xs:attribute name="hostAddress" type="xs:string" use="optional" />
    </xs:complexType>

    <!-- Validate either name or address attribute specified (but not both). -->
    <xs:key name="WebAddressHostNameOrAddressAttributePresent">
        <xs:selector xpath="." />
        <xs:field xpath="@hostName | @hostAddress" />
    </xs:key>
</xs:element>


问:
What is the difference between StreamExecutionEnvironment and StreamTableEnvironment in Flink
Well, I'm a newbie on Apache Flink and reading some source codes on the Internet.

Sometimes I saw StreamExecutionEnvironment but I have also seen StreamTableEnvironment.

I've read the official doc but I still can't figure out their difference.

Furthermore, I'm trying to code a Flink Stream Job, which receives the data from Kafka. In this case, which kind of environment should I use?

答:
A StreamExecutionEnvironment is used with the DataStream API. You need a StreamTableEnvironment if you are going to use the higher level Table or SQL APIs.

The section of the docs on creating a TableEnvironment covers this in more detail.

Which you should use depends on whether you want to work with lower level data streams, or a higher level relational API. Both can be used to implement a streaming job that reads from Kafka.

The documentation includes a pair of code walkthroughs introducing both APIs, which should  help you figure out which API is better suited for your use case. See the DataStream walkthrough and the Table walkthrough.

To learn the DataStream API, spend a day working through the self-paced training. There's also training for Flink SQL. Both are free.


问:
Why do numbers alone on lines do not generate errors (Javascript)
Can someone please explain why these Javascript lines do not generate any errors?
This would generally generate an error in many other languages.
In this case, how are they interpreted by Javascript?

11111111111111111111111;
221.2;
0.11111111111111111111111
4;
5
7,
.22;
.0;
-22;
111111111111111111111/1111111111111111111
+45;
45-12
22+22```

答:
These are expressions, and when you enter an expression in the javascript engine, the engine tries to evaluate the expression. but since these expressions are just numbers and operations, the engine has no problem in figuring their values.

however if u tried this x + 3, it will fail, the engine will try to figure its value, and to figure the value of x + 3, it has to evaluate x but x is not defined, so an error will be thrown.

```<code> Uncaught ReferenceError: x is not defined
</code>```

Edit to give a historical view of the reasons behind such a syntax

That is to say, the JS syntax does not force you to have expressions in a statement. And there is a valid reason for that, and that is js is an interpreted language and many interpreted  languages enable expressions to be be alone and not within statements, to make a REPL session more interactive, making these languages easier to interact with - though from a technical point of view, there is no reason that js or any other interpreted language can not enforce such rules, and from a technical point of a view a compiled language statically typed or not can also provide this convenience.

And while js can enforce such rules, interpreted languages often want to be able to execute code as soon as possible, adding such rules will slow this process - so another reason on why to add such a syntax.

Body:
These are expressions, and when you enter an expression in the javascript engine, the engine tries to evaluate the expression. but since these expressions are just numbers and operations, the engine has no problem in figuring their values.

however if u tried this x + 3, it will fail, the engine will try to figure its value, and to figure the value of x + 3, it has to evaluate x but x is not defined, so an error will be thrown.

 Uncaught ReferenceError: x is not defined

Edit to give a historical view of the reasons behind such a syntax

That is to say, the JS syntax does not force you to have expressions in a statement. And there is a valid reason for that, and that is js is an interpreted language and many interpreted  languages enable expressions to be be alone and not within statements, to make a REPL session more interactive, making these languages easier to interact with - though from a technical point of view, there is no reason that js or any other interpreted language can not enforce such rules, and from a technical point of a view a compiled language statically typed or not can also provide this convenience.

And while js can enforce such rules, interpreted languages often want to be able to execute code as soon as possible, adding such rules will slow this process - so another reason on why to add such a syntax.


答:
You have to return true in onCreateOptionsMenu() and in onOptionsItemSelected() after starting the activity.

The correct way would be like this.

```<code>@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.requestpayment,menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()){
        case R.id.logout:
            Intent intent=new Intent(this,Logout.class);
            this.startActivity(intent);
            return true;
    }
    return super.onOptionsItemSelected(item);
}
</code>```

Title: Activity not opening when clicking menu item

Body:
You have to return true in onCreateOptionsMenu() and in onOptionsItemSelected() after starting the activity.

The correct way would be like this.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.requestpayment,menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()){
        case R.id.logout:
            Intent intent=new Intent(this,Logout.class);
            this.startActivity(intent);
            return true;
    }
    return super.onOptionsItemSelected(item);
}


问:
Should I install redux if I already have installed flutter_redux
I was setting up my app to use redux and had just installed flutter_redux but noticed that class Store was not found to import which should be passed to StoreProvider. After installing redux package separately, imports were available. The site says that redux is a dependency of this library so why should I install redux separately?

答:
flutter_redux is a package for flutter side and can call builder after state change
and redux package is a dart side package for handle state and you should add fultter_redux and redux to your dependency

A set of utilities that allow you to easily consume a Redux Store to
  build Flutter Widgets.

This package is built to work with Redux.dart 3.0.0+.


问:
React conditional rendering only partially happening
I have a react component that is displaying the results of an array as a Badge (from Bootstrap React library). In the condition, I'm checking if the length of array is greater than zero and rendering the results using a map function. I wanted to add additional text to also display on the condition but for some reason it is not displaying the h1 tag yet the badges are being displayed. Why isn't it displaying the h1 tag??

```<code>render() {
   const arr = this.state.items;
   return(
    <Card>
     <Card.Body>
      <div>
       {arr.length > 0 && <h1>Additional Text</h1> &&
        arr.map((item) =>
        <Badge key={item.toString()} pill variant='primary'>
          {item}
        </Badge>
       }
     </div>
    </Card.Body>
   </Card>
);
</code>```

答:
You are using an And short circuit evaluation, which evaluates each expression (before the &&) and returns the outcome if it's falsy, or returns the last one if all others are truthy.

In this case the result of the entire expression is the product of the map when there's an array, since the H1 expression results in an object, which is always truthy.

To render the H1 as well use two separate expressions:

```<code>render() {
   const arr = this.state.items;
   return(
    <Card>
     <Card.Body>
      <div>
       {arr.length > 0 && <h1>Additional Text</h1>}
       {arr.length > 0 &&
        arr.map((item) =>
        <Badge key={item.toString()} pill variant='primary'>
          {item}
        </Badge>
       }
     </div>
    </Card.Body>
   </Card>
);
</code>```

Another option is to move all conditionally rendered expressions to another function, and call it when the expression is truthy:

```<code>renderBadges(arr) {
  return (
    <>
      <h1>Additional Text</h1>
      {arr.map((item) => (
        <Badge key={item.toString()} pill variant='primary'>
          {item}
        </Badge>
      )}
    </>
  );
}

render() {
   const arr = this.state.items;
   return(
    <Card>
     <Card.Body>
      <div>
       {arr.length > 0 && this.renderBadges(arr)}
     </div>
    </Card.Body>
   </Card>
);
</code>```

Body:
I have a react component that is displaying the results of an array as a Badge (from Bootstrap React library). In the condition, I'm checking if the length of array is greater than zero and rendering the results using a map function. I wanted to add additional text to also display on the condition but for some reason it is not displaying the h1 tag yet the badges are being displayed. Why isn't it displaying the h1 tag??

render() {
   const arr = this.state.items;
   return(
    <Card>
     <Card.Body>

       {arr.length > 0 &&
Additional Text
 &&
        arr.map((item) =>
        <Badge key={item.toString()} pill variant='primary'>
          {item}
        </Badge>
       }

    </Card.Body>
   </Card>
);

Body:
You are using an And short circuit evaluation, which evaluates each expression (before the &&) and returns the outcome if it's falsy, or returns the last one if all others are truthy.

In this case the result of the entire expression is the product of the map when there's an array, since the H1 expression results in an object, which is always truthy.

To render the H1 as well use two separate expressions:

render() {
   const arr = this.state.items;
   return(
    <Card>
     <Card.Body>
      <div>
       {arr.length > 0 && <h1>Additional Text</h1>}
       {arr.length > 0 &&
        arr.map((item) =>
        <Badge key={item.toString()} pill variant='primary'>
          {item}
        </Badge>
       }
     </div>
    </Card.Body>
   </Card>
);

Another option is to move all conditionally rendered expressions to another function, and call it when the expression is truthy:

renderBadges(arr) {
  return (
    <>
      <h1>Additional Text</h1>
      {arr.map((item) => (
        <Badge key={item.toString()} pill variant='primary'>
          {item}
        </Badge>
      )}
    </>
  );
}

render() {
   const arr = this.state.items;
   return(
    <Card>
     <Card.Body>
      <div>
       {arr.length > 0 && this.renderBadges(arr)}
     </div>
    </Card.Body>
   </Card>
);


问:
Calling a function declared in a third part gradle file from within the buildscript construct
I;m porting to Grade Kotlin Script the following:

```<code>buildscript {
    repositories {
        maven {
            url = URI("https://plugins.gradle.org/m2/")
        }
    }
    dependencies {
        apply(from = "https://raw.githubusercontent.com/i-net-software/SetupBuilder/master/scripts/SetupBuilderVersion.gradle")
        classpath("gradle.plugin.de.inetsoftware:SetupBuilder:" + setupBuilderVersion())
        classpath "gradle.plugin.io.sdkman:gradle-sdkvendor-plugin:1.2.1"
    }
}
</code>```

where setupBuilderVersion() is a function defined in SetupBuilderVersion.gradle

I tried to declare val buildVersionName: groovy.lang.Closure<Any> by ext before the buildscript and within the dependencies but both failed to work (ext remains unresolved)

How can I solve it?

答:
```<code>buildscript {
   repositories {
        maven { url = uri("https://plugins.gradle.org/m2/") }
   }
   apply(from = "https://raw.githubusercontent.com/i-net-software/SetupBuilder/master/scripts/SetupBuilderVersion.gradle")
   val setupBuilderVersion = project.extensions.extraProperties["setupBuilderVersion"] as groovy.lang.Closure<*>
   println(setupBuilderVersion())
}
</code>```

Body:
I;m porting to Grade Kotlin Script the following:

buildscript {
    repositories {
        maven {
            url = URI("https://plugins.gradle.org/m2/")
        }
    }
    dependencies {
        apply(from = "https://raw.githubusercontent.com/i-net-software/SetupBuilder/master/scripts/SetupBuilderVersion.gradle")
        classpath("gradle.plugin.de.inetsoftware:SetupBuilder:" + setupBuilderVersion())
        classpath "gradle.plugin.io.sdkman:gradle-sdkvendor-plugin:1.2.1"
    }
}

where setupBuilderVersion() is a function defined in SetupBuilderVersion.gradle

I tried to declare val buildVersionName: groovy.lang.Closure<Any> by ext before the buildscript and within the dependencies but both failed to work (ext remains unresolved)

How can I solve it?


问:
Unity play games services cloud save internal error
I have used the same code given by https://github.com/playgameservices/play-games-plugin-for-unity to add the cloud save game functionality, enable save games have been called at the beginning of the code and save games are enabled from the google play console as well. The leaderboards and achievements are working fine.

The OnSaveGameOpened function gets an internal error as SavedGameRequestStatus status.
I am not able to find the cause of this (internal error being received as the status), can anyone help me out please? How can I solve this.

P.S. Serialized data (in the form of bytes[]) was fed into the SaveGame function, serialized using the binary formatter.

Edit:
I was able to debug this further, I get an error on the activation of save games in the play console. I have activated the save games feature and published it (this was done a few days ago). I have also confirmed that the Drive API, Play Games Services API and Play Games Management API are enabled under the API console project. I get following error,

Cannot use snapshots without enabling the 'Saved Game' feature in Play console

log from running on an android mobile.

The answer to this question
Google Play Games :: Cannot Use Snapshots Exception
states that it will activate within 24hrs, but it is not active even after multiple days.

答: The problem was solved. It was not a problem from my end, it took well over 24 hours for the saved game services to activate. The problem solved itself once the saved games were enabled by google (there was no notification that the saved games were enabled, instead the app started working properly).</p>


问:
How to require a property using Json.NET.Schema?
I am trying to create a schema to ensure that outside-supplied JSON is of the following form:

```<code>{ Username: "Aaron" }
</code>```

Right now, I'm creating a Newtonsoft JSchema object in C# by doing:

```<code>var sch = new JSchema()
{
    Type = JSchemaType.Object,
    AllowAdditionalProperties = false,
    Properties =
    {
        {
            "Username",
            new JSchema() { Type = JSchemaType.String }
        }
    }
};
</code>```

This is close, but does not require the presence of the Username property. I've tried the following:

```<code>var sch = new JSchema()
{
    Type = JSchemaType.Object,
    AllowAdditionalProperties = false,
    Properties =
    {
        {
            "Username",
            new JSchema() { Type = JSchemaType.String }
        }
    },
    Required = new List<string> { "Username" }
};
</code>```

But I get:

```<code>Error CS0200 Property or indexer 'JSchema.Required' cannot be assigned to -- it is read only
</code>```

And indeed, the documentation notes that the Required property is read-only:

https://www.newtonsoft.com/jsonschema/help/html/P_Newtonsoft_Json_Schema_JSchema_Required.htm

Am I missing something? Why would the Required property be read-only? How can I require the presence of Username?

答:
The answer from @PinBack from 2017 is incorrect: you can use C# Collection Initialization syntax with read-only list properties, like so:

```<code>var sch = new JSchema()
{
    Type = JSchemaType.Object,
    AllowAdditionalProperties = false,
    Properties =
    {
        {
            "Username",
            new JSchema() { Type = JSchemaType.String }
        }
    },
    Required = // <-- here!
    {
        "Username"
    }
};
</code>```

Body:
I am trying to create a schema to ensure that outside-supplied JSON is of the following form:

{ Username: "Aaron" }

Right now, I'm creating a Newtonsoft JSchema object in C# by doing:

var sch = new JSchema()
{
    Type = JSchemaType.Object,
    AllowAdditionalProperties = false,
    Properties =
    {
        {
            "Username",
            new JSchema() { Type = JSchemaType.String }
        }
    }
};

This is close, but does not require the presence of the Username property. I've tried the following:

var sch = new JSchema()
{
    Type = JSchemaType.Object,
    AllowAdditionalProperties = false,
    Properties =
    {
        {
            "Username",
            new JSchema() { Type = JSchemaType.String }
        }
    },
    Required = new List<string> { "Username" }
};

But I get:

Error CS0200 Property or indexer 'JSchema.Required' cannot be assigned to -- it is read only

And indeed, the documentation notes that the Required property is read-only:

https://www.newtonsoft.com/jsonschema/help/html/P_Newtonsoft_Json_Schema_JSchema_Required.htm

Am I missing something? Why would the Required property be read-only? How can I require the presence of Username?

Body:
The answer from @PinBack from 2017 is incorrect: you can use C# Collection Initialization syntax with read-only list properties, like so:

var sch = new JSchema()
{
    Type = JSchemaType.Object,
    AllowAdditionalProperties = false,
    Properties =
    {
        {
            "Username",
            new JSchema() { Type = JSchemaType.String }
        }
    },
    Required = // <-- here!
    {
        "Username"
    }
};


问:
How to draw line with brush on image with PyQt5
I want to draw a line (or paint) on an image that I already opened. I can open the image, but I can't draw on the image. But if I don't open any image, I can draw anything I want on blank space.

So, How can I draw with a brush on an image ? For now eraser or etc. It's not important. I just want to do something with a brush on an image, which image I already open in my computer.

I didn't get any error or something. So I can't search specifically.

Here is my code;

```<code>from PyQt5.QtWidgets import QMainWindow, QApplication, QMenu, QMenuBar, QAction, QFileDialog, QLabel
from PyQt5.QtGui import QIcon, QImage, QPainter, QPen, QBrush, QPixmap
from PyQt5.QtCore import Qt, QPoint
import sys

class Window(QMainWindow):
    def __init__(self):
        super().__init__()

        title = "Paint Application"
        top = 400
        left = 400
        width = 800
        height = 600

        icon = "icons/pain.png"

        self.setWindowTitle(title)
        self.setGeometry(top, left, width, height)
        self.setWindowIcon(QIcon(icon))

        self.image = QImage(self.size(), QImage.Format_RGB32)
        self.image.fill(Qt.white)

        self.drawing = False
        self.brushSize = 2
        self.brushColor = Qt.black
        self.lastPoint = QPoint()

        mainMenu = self.menuBar()
        fileMenu = mainMenu.addMenu("File")
        brushSize = mainMenu.addMenu("Brush Size")
        brushColor = mainMenu.addMenu("Brush Color")

        openAction = QAction('Open Image', self)
        openAction.triggered.connect(self.openImage)
        fileMenu.addAction(openAction)

        closeAction = QAction('Exit', self)
        closeAction.triggered.connect(self.close)
        fileMenu.addAction(closeAction)
        self.label = QLabel()
        self.setCentralWidget(self.label)

        saveAction = QAction(QIcon("icons/save.png"), "Save",self)
        saveAction.setShortcut("Ctrl+S")
        fileMenu.addAction(saveAction)
        saveAction.triggered.connect(self.save)

        clearAction = QAction(QIcon("icons/clear.png"), "Clear", self)
        clearAction.setShortcut("Ctrl+C")
        fileMenu.addAction(clearAction)
        clearAction.triggered.connect(self.clear)

        threepxAction = QAction( QIcon("icons/threepx.png"), "3px", self)
        brushSize.addAction(threepxAction)
        threepxAction.triggered.connect(self.threePixel)

        fivepxAction = QAction(QIcon("icons/fivepx.png"), "5px", self)
        brushSize.addAction(fivepxAction)
        fivepxAction.triggered.connect(self.fivePixel)

        sevenpxAction = QAction(QIcon("icons/sevenpx.png"),"7px", self)
        brushSize.addAction(sevenpxAction)
        sevenpxAction.triggered.connect(self.sevenPixel)

        ninepxAction = QAction(QIcon("icons/ninepx.png"), "9px", self)
        brushSize.addAction(ninepxAction)
        ninepxAction.triggered.connect(self.ninePixel)

        blackAction = QAction(QIcon("icons/black.png"), "Black", self)
        blackAction.setShortcut("Ctrl+B")
        brushColor.addAction(blackAction)
        blackAction.triggered.connect(self.blackColor)

        whitekAction = QAction(QIcon("icons/white.png"), "White", self)
        whitekAction.setShortcut("Ctrl+W")
        brushColor.addAction(whitekAction)
        whitekAction.triggered.connect(self.whiteColor)

        redAction = QAction(QIcon("icons/red.png"), "Red", self)
        redAction.setShortcut("Ctrl+R")
        brushColor.addAction(redAction)
        redAction.triggered.connect(self.redColor)

        greenAction = QAction(QIcon("icons/green.png"), "Green", self)
        greenAction.setShortcut("Ctrl+G")
        brushColor.addAction(greenAction)
        greenAction.triggered.connect(self.greenColor)

        yellowAction = QAction(QIcon("icons/yellow.png"), "Yellow", self)
        yellowAction.setShortcut("Ctrl+Y")
        brushColor.addAction(yellowAction)
        yellowAction.triggered.connect(self.yellowColor)

    def openImage(self):
        imagePath, _ = QFileDialog.getOpenFileName()
        pixmap = QPixmap(imagePath)
        self.label.setPixmap(pixmap)
        self.resize(pixmap.size())
        self.adjustSize()

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.drawing = True
            self.lastPoint = event.pos()
            #print(self.lastPoint)

    def mouseMoveEvent(self, event):
        if(event.buttons() & Qt.LeftButton) & self.drawing:
            painter = QPainter(self.image)
            painter.setPen(QPen(self.brushColor, self.brushSize, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
            painter.drawLine(self.lastPoint, event.pos())
            self.lastPoint = event.pos()
            self.update()

    def mouseReleaseEvent(self, event):

        if event.button() == Qt.LeftButton:
            self.drawing = False

    def paintEvent(self, event):
        canvasPainter  = QPainter(self)
        canvasPainter.drawImage(self.rect(),self.image, self.image.rect() )

    def save(self):
        filePath, _ = QFileDialog.getSaveFileName(self, "Save Image", "", "PNG(*.png);;JPEG(*.jpg *.jpeg);;All Files(*.*) ")

        if filePath == "":
            return
        self.image.save(filePath)

    def clear(self):
        self.image.fill(Qt.white)
        self.update()

    def threePixel(self):
        self.brushSize = 3

    def fivePixel(self):
        self.brushSize = 5

    def sevenPixel(self):
        self.brushSize = 7

    def ninePixel(self):
        self.brushSize = 9

    def blackColor(self):
        self.brushColor = Qt.black

    def whiteColor(self):
        self.brushColor = Qt.white

    def redColor(self):
        self.brushColor = Qt.red

    def greenColor(self):
        self.brushColor = Qt.green

    def yellowColor(self):
        self.brushColor = Qt.yellow

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = Window()
    window.show()
app.exec()
</code>```

答:
Instead of constructing a QPixmap from the filepath, construct a QImage and assign it to the variable self.image. You won't have to change anything else as the paintEvent will draw the QImage object that pointed to by self.image.

```<code>def openImage(self):
    imagePath, _ = QFileDialog.getOpenFileName()
    self.image = QImage(imagePath)
    self.resize(self.image.size())
</code>```

Body:
I want to draw a line (or paint) on an image that I already opened. I can open the image, but I can't draw on the image. But if I don't open any image, I can draw anything I want on blank space.

So, How can I draw with a brush on an image ? For now eraser or etc. It's not important. I just want to do something with a brush on an image, which image I already open in my computer.

I didn't get any error or something. So I can't search specifically.

Here is my code;

from PyQt5.QtWidgets import QMainWindow, QApplication, QMenu, QMenuBar, QAction, QFileDialog, QLabel
from PyQt5.QtGui import QIcon, QImage, QPainter, QPen, QBrush, QPixmap
from PyQt5.QtCore import Qt, QPoint
import sys

class Window(QMainWindow):
    def __init__(self):
        super().__init__()

        title = "Paint Application"
        top = 400
        left = 400
        width = 800
        height = 600

        icon = "icons/pain.png"

        self.setWindowTitle(title)
        self.setGeometry(top, left, width, height)
        self.setWindowIcon(QIcon(icon))

        self.image = QImage(self.size(), QImage.Format_RGB32)
        self.image.fill(Qt.white)

        self.drawing = False
        self.brushSize = 2
        self.brushColor = Qt.black
        self.lastPoint = QPoint()

        mainMenu = self.menuBar()
        fileMenu = mainMenu.addMenu("File")
        brushSize = mainMenu.addMenu("Brush Size")
        brushColor = mainMenu.addMenu("Brush Color")

        openAction = QAction('Open Image', self)
        openAction.triggered.connect(self.openImage)
        fileMenu.addAction(openAction)

        closeAction = QAction('Exit', self)
        closeAction.triggered.connect(self.close)
        fileMenu.addAction(closeAction)
        self.label = QLabel()
        self.setCentralWidget(self.label)

        saveAction = QAction(QIcon("icons/save.png"), "Save",self)
        saveAction.setShortcut("Ctrl+S")
        fileMenu.addAction(saveAction)
        saveAction.triggered.connect(self.save)

        clearAction = QAction(QIcon("icons/clear.png"), "Clear", self)
        clearAction.setShortcut("Ctrl+C")
        fileMenu.addAction(clearAction)
        clearAction.triggered.connect(self.clear)

        threepxAction = QAction( QIcon("icons/threepx.png"), "3px", self)
        brushSize.addAction(threepxAction)
        threepxAction.triggered.connect(self.threePixel)

        fivepxAction = QAction(QIcon("icons/fivepx.png"), "5px", self)
        brushSize.addAction(fivepxAction)
        fivepxAction.triggered.connect(self.fivePixel)

        sevenpxAction = QAction(QIcon("icons/sevenpx.png"),"7px", self)
        brushSize.addAction(sevenpxAction)
        sevenpxAction.triggered.connect(self.sevenPixel)

        ninepxAction = QAction(QIcon("icons/ninepx.png"), "9px", self)
        brushSize.addAction(ninepxAction)
        ninepxAction.triggered.connect(self.ninePixel)

        blackAction = QAction(QIcon("icons/black.png"), "Black", self)
        blackAction.setShortcut("Ctrl+B")
        brushColor.addAction(blackAction)
        blackAction.triggered.connect(self.blackColor)

        whitekAction = QAction(QIcon("icons/white.png"), "White", self)
        whitekAction.setShortcut("Ctrl+W")
        brushColor.addAction(whitekAction)
        whitekAction.triggered.connect(self.whiteColor)

        redAction = QAction(QIcon("icons/red.png"), "Red", self)
        redAction.setShortcut("Ctrl+R")
        brushColor.addAction(redAction)
        redAction.triggered.connect(self.redColor)

        greenAction = QAction(QIcon("icons/green.png"), "Green", self)
        greenAction.setShortcut("Ctrl+G")
        brushColor.addAction(greenAction)
        greenAction.triggered.connect(self.greenColor)

        yellowAction = QAction(QIcon("icons/yellow.png"), "Yellow", self)
        yellowAction.setShortcut("Ctrl+Y")
        brushColor.addAction(yellowAction)
        yellowAction.triggered.connect(self.yellowColor)

    def openImage(self):
        imagePath, _ = QFileDialog.getOpenFileName()
        pixmap = QPixmap(imagePath)
        self.label.setPixmap(pixmap)
        self.resize(pixmap.size())
        self.adjustSize()

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.drawing = True
            self.lastPoint = event.pos()
            #print(self.lastPoint)

    def mouseMoveEvent(self, event):
        if(event.buttons() & Qt.LeftButton) & self.drawing:
            painter = QPainter(self.image)
            painter.setPen(QPen(self.brushColor, self.brushSize, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
            painter.drawLine(self.lastPoint, event.pos())
            self.lastPoint = event.pos()
            self.update()

    def mouseReleaseEvent(self, event):

        if event.button() == Qt.LeftButton:
            self.drawing = False

    def paintEvent(self, event):
        canvasPainter  = QPainter(self)
        canvasPainter.drawImage(self.rect(),self.image, self.image.rect() )

    def save(self):
        filePath, _ = QFileDialog.getSaveFileName(self, "Save Image", "", "PNG(*.png);;JPEG(*.jpg *.jpeg);;All Files(*.*) ")

        if filePath == "":
            return
        self.image.save(filePath)

    def clear(self):
        self.image.fill(Qt.white)
        self.update()

    def threePixel(self):
        self.brushSize = 3

    def fivePixel(self):
        self.brushSize = 5

    def sevenPixel(self):
        self.brushSize = 7

    def ninePixel(self):
        self.brushSize = 9

    def blackColor(self):
        self.brushColor = Qt.black

    def whiteColor(self):
        self.brushColor = Qt.white

    def redColor(self):
        self.brushColor = Qt.red

    def greenColor(self):
        self.brushColor = Qt.green

    def yellowColor(self):
        self.brushColor = Qt.yellow

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = Window()
    window.show()
app.exec()

Body:
Instead of constructing a QPixmap from the filepath, construct a QImage and assign it to the variable self.image. You won't have to change anything else as the paintEvent will draw the QImage object that pointed to by self.image.

def openImage(self):
    imagePath, _ = QFileDialog.getOpenFileName()
    self.image = QImage(imagePath)
    self.resize(self.image.size())


问:
Is it possible to call a function defined inside another function in Python?
For example:

def foo():
    def bar():
        return

    # some code
    return

def foo2():
    # call bar() here?
```

Is it possible to put bar() inside foo() and call it in foo2()?

答:
Somewhat, you can do that - by declaring bar global:

```<code>def foo():
   global bar
   def bar():
      print("In bar")
</code>```

But you cannot call bar unless you first call foo, because that's the function that defines bar:

```<code>bar()
#Traceback (most recent call last):
#  File "<stdin>", line 1, in <module>
#NameError: name 'bar' is not defined
foo()
bar()
#In bar
</code>```

Overall, this is a very bad idea.

Body:
For example:

def foo():
    def bar():
        return

    # some code
    return

def foo2():
    # call bar() here?

Is it possible to put bar() inside foo() and call it in foo2()?

Body:
Somewhat, you can do that - by declaring bar global:

def foo():
   global bar
   def bar():
      print("In bar")

But you cannot call bar unless you first call foo, because that's the function that defines bar:

bar()
#Traceback (most recent call last):
#  File "<stdin>", line 1, in <module>
#NameError: name 'bar' is not defined
foo()
bar()
#In bar

Overall, this is a very bad idea.


问:
QML - Display "Next" button to move to next TextField on a mobile keyboard
How can I force my keyboard layout to display the "Next" button in QML ? ( Like in a standard HTML form )
I don't want to display a "OK" button ( which means that you're about to validate the form .. )</p>

答:
I assumed you not used Qt Virtual Keyboard. So you can set action button type through EnterKey.type attached property (available types are Go, Search, Send, Next,...).

Also you need to handle return button pressed signal to do what you want. For example, sending data. In your case you want just switch focus to next control.

```<code>import QtQuick 2.12
import QtQuick.Controls 1.12

Column {
    TextField {
        id: field1
        KeyNavigation.tab: field2
        activeFocusOnTab: true
        Keys.onReturnPressed: KeyNavigation.tab.forceActiveFocus();
    }
    TextField {
        id: field2
        KeyNavigation.tab: field3
        activeFocusOnTab: true
        Keys.onReturnPressed: KeyNavigation.tab.forceActiveFocus();
    }
    TextField {
        id: field3
        KeyNavigation.tab: field1
        activeFocusOnTab: true
        Keys.onReturnPressed: KeyNavigation.tab.forceActiveFocus();
    }
}
</code>```

I handled returnPressed signal to switch focus. Also I made it possible to switch using TAB key for Desktop platforms.

Body:
I assumed you not used Qt Virtual Keyboard. So you can set action button type through EnterKey.type attached property (available types are Go, Search, Send, Next,...).

Also you need to handle return button pressed signal to do what you want. For example, sending data. In your case you want just switch focus to next control.

import QtQuick 2.12
import QtQuick.Controls 1.12

Column {
    TextField {
        id: field1
        KeyNavigation.tab: field2
        activeFocusOnTab: true
        Keys.onReturnPressed: KeyNavigation.tab.forceActiveFocus();
    }
    TextField {
        id: field2
        KeyNavigation.tab: field3
        activeFocusOnTab: true
        Keys.onReturnPressed: KeyNavigation.tab.forceActiveFocus();
    }
    TextField {
        id: field3
        KeyNavigation.tab: field1
        activeFocusOnTab: true
        Keys.onReturnPressed: KeyNavigation.tab.forceActiveFocus();
    }
}

I handled returnPressed signal to switch focus. Also I made it possible to switch using TAB key for Desktop platforms.


问:
Typescript: How do I declare a generic class factory that maps enums to types in the safest way?
I am trying to figure out the best way to assign types to this generic class factory.
I've copied some of this code from another question: https://stackoverflow.com/a/47933133
It's relatively straightforward to map an enum value to a class. I can't however seem to figure out how to go one step further and type my creation method so that it realizes if the class I am creating does not in fact take the parameters that I've passed in.
(I realize this is a convoluted and contrived way to construct an instance. I think I've distilled down something I'm trying to do in my app in the real world to this question though.)

class Dog {
    public dogName: string = ""
    public init(params: DogParams) { }
}
class Cat {
    public catName: string = ""
    public init(params: CatParams) { }
}
class DogParams { public dogValues: number = 0 }
class CatParams { public catValue: number = 0}

enum Kind {
    DogKind = 'DogKind',
    CatKind = 'CatKind',
}

const kindMap = {
    [Kind.DogKind]: Dog,
    [Kind.CatKind]: Cat,
};
type KindMap = typeof kindMap;

const paramsMap = {
    [Kind.DogKind]: DogParams,
    [Kind.CatKind]: CatParams,
}
type ParamsMap = typeof paramsMap;

function getAnimalClasses<K extends Kind>(key: K, params: ParamsMap[K]): [KindMap[K], ParamsMap[K]] {
    const klass = kindMap[key];
    return [klass, params];
}

// Cool: Typescript knows that dogStuff is of type [typeof Dog, typeof DogParams]
const dogStuff = getAnimalClasses(Kind.DogKind, DogParams);

// Now imagine I want to instantiate and init my class in a type-safe way:
function getAnimalInstance<K extends Kind>(key: K, params: InstanceType<ParamsMap[K]>): InstanceType<KindMap[K]> {
    const animalKlass = kindMap[key];

    // animalInstance : Dog | Cat
    const animalInstance = new animalKlass() as InstanceType<KindMap[K]>;

    // By this line, Typescript just knows that animalInstance has a method called init that takes `DogParams & CatParams`. That makes sense to me, but it's not what I want.
    // QUESTION: The following gives an error. Is there a type-safe way that I can make this method call and ensure that my maps and my `init` method signatures are
    // are consistent throughout my app? Do I need more generic parameters of this function?
    animalInstance.init(params);

    return animalInstance;
}

// This works too: It knows that I have to pass in CatParams if I am passing in CatKind
// It also knows that `cat` is an instance of the `Cat` class.
const cat = getAnimalInstance(Kind.CatKind, new CatParams());
```

<p>Playground Link</p>

<p>See the actual question in the code above.</p>

<hr>

<p><strong>UPDATE May 29, 2020:</strong></p>

<p>@Kamil Szot points out that I don't have proper type safety in my non-overloaded function in the first place: </p>

```    // Should be an error but is not:
    const cat = getAnimalInstance((() => Kind.DogKind)(), new CatParams());
```

<p>So, we really do need overloads, as he suggests, but I don't want to write them manually. So, here's what I've got now. I think that this is as good as it's going to get, but I wish I could define another type that made auto-generating these overloads less verbose and made it so that I didn't have to duplicate the function signature of my function implementation twice.</p>

```// We can use UnionToIntersection to auto-generate our overloads
// Learned most of this technique here: https://stackoverflow.com/a/53173508/544130
type UnionToIntersection = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never

const autoOverloadedCreator: UnionToIntersection<
    Kind extends infer K ?
    K extends Kind ?
    // I wish there was a way not to have to repeat the signature of getAnimalInstance here though!
    (key: K, p: InstanceType<ParamsMap[K]>) => InstanceType<KindMap[K]> :
    never : never
> = getAnimalInstance;

// This works, and has overload intellisense!
let cat2 = autoOverloadedCreator(Kind.CatKind, new CatParams());

// And this properly gives an error
const yayThisIsAnErrorAlso = autoOverloadedCreator((() => Kind.DogKind)(), new CatParams());

// Note that this type is different from our ManuallyOverloadedFuncType though:
// type createFuncType = ((key: Kind.DogKind, p: DogParams) => Dog) & ((key: Kind.CatKind, p: CatParams) => Cat)
type CreateFuncType = typeof autoOverloadedCreator;
```

Playground Link

答:
Another simpler general solution Playground link

```<code>class Dog {
    public dogName: string = ""
    public init(params: DogParams) { }
}
class Cat {
    public catName: string = ""
    public init(params: CatParams) { }
}
class DogParams { public dogValues: number = 0 }
class CatParams { public catValue: number = 0}

enum Kind {
    DogKind = 'DogKind',
    CatKind = 'CatKind',
}

const kindMap = {
    [Kind.DogKind]: Dog,
    [Kind.CatKind]: Cat,
};
type KindMap = typeof kindMap;

const paramsMap = {
    [Kind.DogKind]: DogParams,
    [Kind.CatKind]: CatParams,
}
type ParamsMap = typeof paramsMap;

type Tuples<T> = T extends Kind ? [T, InstanceType<KindMap[T]>, InstanceType<ParamsMap[T]>] : never;
type SingleKinds<K> = [K] extends (K extends Kind ? [K] : never) ? K : never;
type ClassType<A extends Kind> = Extract<Tuples<Kind>, [A, any, any]>[1];
type ParamsType<A extends Kind> = Extract<Tuples<Kind>, [A, any, any]>[2];

function getAnimalInstance<A extends Kind>(key:SingleKinds<A>, params: ParamsType<A>): ClassType<A> {
    const animalKlass: ClassType<A> = kindMap[key];

    const animalInstance = new animalKlass();

    animalInstance.init(params);
    return animalInstance;
}

// this works
const cat = getAnimalInstance(Kind.CatKind, new CatParams());

const shouldBeError = getAnimalInstance(Kind.DogKind, new CatParams()); // wrong params
const shouldBeErrorToo = getAnimalInstance(f(), new CatParams());       // undetermined kind
const shouldBeErrorAlso = getAnimalInstance(f(), new DogParams());      // undetermined kind

var k:Kind;
k = Kind.CatKind;

const suprisinglyACat = getAnimalInstance(k, new CatParams());    // even that works!
const shouldError = getAnimalInstance(k, new DogParams());

function f():Kind {
    return Kind.DogKind;
}
</code>```

And another example of this written to mirror my other answer that required manual overloads. It also automatically gets Params types without needing separate manually defined map.

Playground link

```<code>class DogParam { public n: number = 0; }
class CatParam { public n: string = "a"; }
class BatParam { public n: boolean = true; }

class Dog { init(p: DogParam) { } }
class Cat { init(p: CatParam) { } }
class Bat { init(p: BatParam) { } }

enum Kind { Dog, Cat, Bat }

const kindMap = {
    [Kind.Dog]: Dog,
    [Kind.Cat]: Cat,
    [Kind.Bat]: Bat
}

type Tuples<K = Kind> = K extends Kind ? [
    K,
    InstanceType<(typeof kindMap)[K]>,
    InstanceType<(typeof kindMap)[K]> extends
        { init: (a: infer P) => any } ? P : never
] : never;
type SingleKinds<K> = [K] extends (K extends Kind ? [K] : never) ? K : never;
type ClassType<K> = Extract<Tuples, [K, any, any]>[1];
type ParamsType<K> = Extract<Tuples, [K, any, any]>[2];

function a<K extends Kind>(k: SingleKinds<K>, p: ParamsType<K>): ClassType<K> {
    var ins:ClassType<K> = new kindMap[k];
    ins.init(p);
    return ins;
}

function f(): Kind {
    return Kind.Cat;
}

var k:Kind;
k = Kind.Cat;

a(Kind.Dog, new DogParam()); // works
a(Kind.Cat, new DogParam()); // error because mismatch
a(f(), new DogParam());      // error because kind undetermined
a(f(), new CatParam());      // error because kind undetermined
a(f() as Kind.Dog, new DogParam());      // works, but hey, it's your fault
                                        // doing the wrong cast here manually
a(k, new CatParam());   // even this works
a(k, new DogParam());   // and this error

// you need to use exactly one kind at a time or it errors
var mixed: Kind.Dog | Kind.Cat = null as any;
var b = a(mixed, new DogParam());

var mixedfn = ():Kind.Dog | Kind.Cat => null as any;
var b = a(mixedfn(), new DogParam());
</code>```

Solution that merges both my and Taytay ideas that generates everything it needs from "kinds to classes" map and uses automatically generated functions overload to provide nice intellisense Playground link

```<code>class Dog {
    public dogName: string = ""
    public init(params: DogParams) { }
}
class Cat {
    public catName: string = ""
    public init(params: CatParams) { }
}
class DogParams { public dogValues: number = 0 }
class CatParams { public catValue: number = 0}

enum Kind {
    DogKind = 'DogKind',
    CatKind = 'CatKind',
}

const kindMap = {
    [Kind.DogKind]: Dog,
    [Kind.CatKind]: Cat,
};
type KindMap = typeof kindMap;

type Tuples<K = Kind> = K extends Kind ? [
    K,
    InstanceType<KindMap[K]>,
    InstanceType<(typeof kindMap)[K]> extends
        { init: (a: infer P) => any } ? P : never
] : never;

type ClassType<K> = Extract<Tuples, [K, any, any]>[1];
type ParamsType<K> = Extract<Tuples, [K, any, any]>[2];

type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never
type Fnc<T = Tuples> = UnionToIntersection<
    T extends Tuples ? (key: T[0], p: T[2]) => T[1] : never
>;
var getAnimalInstance:Fnc = function<K extends Kind>(key: K, params:ParamsType<K>):ClassType<K> {
    const animalKlass = kindMap[key];

    const animalInstance = new animalKlass();

    animalInstance.init(params);

    return animalInstance;
}

// works
const cat = getAnimalInstance(Kind.CatKind, new CatParams());

// errors
const shouldBeError = getAnimalInstance((() => Kind.DogKind)(), new CatParams());
</code>```

User Taytay who asked the question did an investigation of this code here Playground link to determine how it works.

Body:
I am trying to figure out the best way to assign types to this generic class factory.
I've copied some of this code from another question: https://stackoverflow.com/a/47933133
It's relatively straightforward to map an enum value to a class. I can't however seem to figure out how to go one step further and type my creation method so that it realizes if the class I am creating does not in fact take the parameters that I've passed in.
(I realize this is a convoluted and contrived way to construct an instance. I think I've distilled down something I'm trying to do in my app in the real world to this question though.)

class Dog {
    public dogName: string = ""
    public init(params: DogParams) { }
}
class Cat {
    public catName: string = ""
    public init(params: CatParams) { }
}
class DogParams { public dogValues: number = 0 }
class CatParams { public catValue: number = 0}

enum Kind {
    DogKind = 'DogKind',
    CatKind = 'CatKind',
}

const kindMap = {
    [Kind.DogKind]: Dog,
    [Kind.CatKind]: Cat,
};
type KindMap = typeof kindMap;

const paramsMap = {
    [Kind.DogKind]: DogParams,
    [Kind.CatKind]: CatParams,
}
type ParamsMap = typeof paramsMap;

function getAnimalClasses<K extends Kind>(key: K, params: ParamsMap[K]): [KindMap[K], ParamsMap[K]] {
    const klass = kindMap[key];
    return [klass, params];
}

// Cool: Typescript knows that dogStuff is of type [typeof Dog, typeof DogParams]
const dogStuff = getAnimalClasses(Kind.DogKind, DogParams);

// Now imagine I want to instantiate and init my class in a type-safe way:
function getAnimalInstance<K extends Kind>(key: K, params: InstanceType<ParamsMap[K]>): InstanceType<KindMap[K]> {
    const animalKlass = kindMap[key];

    // animalInstance : Dog | Cat
    const animalInstance = new animalKlass() as InstanceType<KindMap[K]>;

    // By this line, Typescript just knows that animalInstance has a method called init that takes `DogParams & CatParams`. That makes sense to me, but it's not what I want.
    // QUESTION: The following gives an error. Is there a type-safe way that I can make this method call and ensure that my maps and my `init` method signatures are
    // are consistent throughout my app? Do I need more generic parameters of this function?
    animalInstance.init(params);

    return animalInstance;
}

// This works too: It knows that I have to pass in CatParams if I am passing in CatKind
// It also knows that `cat` is an instance of the `Cat` class.
const cat = getAnimalInstance(Kind.CatKind, new CatParams());

<a href="https://www.typescriptlang.org/play/?ssl=1&ssc=1&pln=57&pc=62#code/MYGwhgzhAEAiD2BzaBvAUNT0AOBXARiAJbDQAmSAcmALYCmAXNBAC4BORAdsgLzQBE-DFjyES0LkRYAKbGDa0ITBIgAK8xQEpU0AL5p9oSDADCYFqmGZRxUsHPV6TVh27Q+gqzgK2JnKbIaNErQZizqCsHaKHoGaEZQcEgRijo24hSIAGpgILh0IZy4NPh0bO7QAAyxCabmKcFpPuL2LDl5jNBFJWUVlfpodN3QANJcZJZYSYhjnBN8AOQqs2QLADReYSsVC1vj63Hx8Jys0ADW4wCyYNgV6FMA2isAdMvjALrKSBuPL3tzn1C5g2ugA3GgWABPbB0UZXG4VKEw+AAM3O8Ow4KOJwsckiEGutz49ywT3GryQK0BKgaEB+pL+5ipTDCtJBEOhsNphMRnNROCCBJuWJRuE4wBYRGO0EQdBYAEF-DRciZwFACgAeEbQOgADxYQzIMBWAD5pGc6JCmCM1gL8UxuTcnu9NEwyXNCc7bY7sM73pMsMBjqczmqYHwLh6nRbIe9wVM2HLcGxONAHqHjLa8Yo44cAPR50LweAgJgAFU5EGAHGwFjOnHgAHcYCwABbmchIADKLFwKLRRBg-KRsIeI-5Klt47RNMF72xp0yPb7aL4soVSpVYYK0hebzmttn+M0WIL0EoTYkysQXFhAEloI2wJwLCx4H5WM-JeZYc+JpILBoSFoFqPxoDAaARwAWggMAUVhJ8rTQUVxUlaV10VIhlRAO8cWfYA6C1HV9UNY1xjWM0Y2tLNBSYXDP3FOgKxhDUfWdE1XWgeiWHwpjOS1DF2IDTAgxxcDNxAEYwwqSMyE9GNcymUTTmzYIpOMCpVKFX0FKxKYz2fLDcm43joC+ZAAB8gRYLxlIsQzsJMxiKk4OhG3EozJLDaRtEgLi8MY5jCJWT0RneE14ywM8tKcgjzNpaArNZQVbODXFBVi2E+Fc9ytPUqAfPAmBMqC1jBVC8K9KiwsACFgLbQdoGIVzbSCqsawsAArXAQwbZtIPbeyJMy6B2xgCD6DbeAJnsEAQDof9-FfQbILAC0YAAAyPVIADJrNpDbnmgMsVuVdbmCGCBYTfaB6FtfBcAsKQFhgBsLEbFaHyfF9ni8M8AEUAFUAFEuzLO8AHlKHLVtYRREsQCbLhkBvAA3ApxJ1Ng2HgNgjrvFtYcTcDIM5GC4IQsB6s+kDn1utbrtbRrJtbababm8SJku5NGY7ID6ewca5lu4CNoAjbbrlVmJggIhEE4cwefG4m-sLeRYWUwcDRfAacdwRBWcekXwOwbAAH4ki4ro6AW27cdhWVXI4UhVLlMohzRBqYBQiUpU4M2vAc4yAoI54AMCfFMpPNAvETXsUw8xyQ7ocEBjPE7GsbXGzhbYs6LrPrCY7B923RyD3zkRIuH2wUJDRB9aAFKBkbA-4yDQM873skAIHfesmyLiwNtaCXGrprgGII6Bh1h6ANrCCXal+uzaYsNc5UwpPJ7oXdyTb20cpr-EfJPIA" rel="nofollow noreferrer">Playground Link

See the actual question in the code above.

UPDATE May 29, 2020:

@Kamil Szot points out that I don't have proper type safety in my non-overloaded function in the first place:

    // Should be an error but is not:
    const cat = getAnimalInstance((() => Kind.DogKind)(), new CatParams());

So, we really do need overloads, as he suggests, but I don't want to write them manually. So, here's what I've got now. I think that this is as good as it's going to get, but I wish I could define another type that made auto-generating these overloads less verbose and made it so that I didn't have to duplicate the function signature of my function implementation twice.

// We can use UnionToIntersection to auto-generate our overloads
// Learned most of this technique here: https://stackoverflow.com/a/53173508/544130
type UnionToIntersection = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never

const autoOverloadedCreator: UnionToIntersection<
    Kind extends infer K ?
    K extends Kind ?
    // I wish there was a way not to have to repeat the signature of getAnimalInstance here though!
    (key: K, p: InstanceType<ParamsMap[K]>) => InstanceType<KindMap[K]> :
    never : never
> = getAnimalInstance;

// This works, and has overload intellisense!
let cat2 = autoOverloadedCreator(Kind.CatKind, new CatParams());

// And this properly gives an error
const yayThisIsAnErrorAlso = autoOverloadedCreator((() => Kind.DogKind)(), new CatParams());

// Note that this type is different from our ManuallyOverloadedFuncType though:
// type createFuncType = ((key: Kind.DogKind, p: DogParams) => Dog) & ((key: Kind.CatKind, p: CatParams) => Cat)
type CreateFuncType = typeof autoOverloadedCreator;

<a href="https://www.typescriptlang.org/play/?ssl=1&ssc=1&pln=103&pc=1#code/MYGwhgzhAEAiD2BzaBvAUNT0AOBXARiAJbDQAmSAcmALYCmAXNBAC4BORAdsgLzQBE-DFjyES0LkRYAKbGDa0ITBIgAK8xQEpU0AL5p9oSDADCYFqmGZRxUsHPV6TVh27Q+gqzgK2JnKbIaNErQZizqCsHaKHoGaEZQcEgRijo24hSIAGpgILh0IZy4NPh0bO7QAAyxCabmKcFpPuL2LDl5jNBFJWUVlfpodN3QANJcZJZYSYhjnBN8AOQqs2QLADReYSsVC1vj63Hx8Jys0ADW4wCyYNgV6FMA2isAdMvjALrKSBuPL3tzn1C5g2ugA3GgWABPbB0UZXG4VKEw+AAM3O8Ow4KOJwsckiEGutz49ywT3GryQK0BKgaEB+pL+5ipTDCtJBEOhsNphMRnNROCCBJuWJRuE4wBYRGO0EQdBYAEF-DRciZwFACgAeEbQOgADx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yO6XgI2sglG7FjLEhM7RE8VjT00PR+eizF6wsiuStse6vothBQNTF-ZZI5QCp3VGC1flKJABsijZA9nigObSu9tczxeVwfg9zwBPNhsfVadTYinEqSiGplQ2h1IFqfep55rypFqbCMgryLa6CBeC55PkaJyPUsU+o5TMK0BAA" rel="nofollow noreferrer">Playground Link

Body:
Another simpler general solution <a href="https://www.typescriptlang.org/play?ssl=1&ssc=1&pln=61&pc=1#code/FAYwNghgzlAEAiB7A5rA3sWXYAcCuARmAJYiwAmKAchALYCmAXLFAC4BOxAdqgLywAiAZmz4ipWN2KsAFDgjs6UZkmQAFBUoCU6WAF9gB8NDgBhCK3QisYkmRAWaDZm049Y-IddyE7krtJymrTKsOasGoohOmj6hqCQMAgokUq6thKUyABqEGB49KFceLQE9OwesAAMccZJ4akh6b4SDqy5+UywxaXllVUGwPQ9sADS3ORW2MnI41yT-ADkqnPkiwA03uGrlYvbExvxoIhcbLAA1hMAshA4lRjTANqrAHQrEwC6KiibT6-78y+YQsmz0AG5gKwAJ44ehja63SrQ2GIABmFwROAhx1OlnkUSgNzu-Ae2GeEzeKFWQNUjSgvzJ-ws1OYDWC9PiyLhdKJSJh9DRuHZROxXNgABU8DgwIUADzigB8lXFsHoAA9WMNyHAdgB+WCPcXrWAASVxEC4IHo4v5stWRMNHwVxrNbAtVptsNlPNujoVH1gzC49AAbuUIWKAMrcZAy1ZQO1K-jPAPqzXzOAyUaqjVanUTWD6lOB7qh8o6fXZoNl9gR-lhRJQT30WUAQRz6e18PmSdgAFENYoQKx5VKZQnVs6Da3jRaobOuFCnY8AIwfOuw2B05ttjt57vkXsDjgQYej6VyyfGx4z2BzhdLhWPABM6+AwFReEtrGIJ1gyHoVhWwCWg8ldVh3Rbds033ScZHOegoUYaMeDjCYE1bKd8SUZht1tTCtFZRsd0wqZsBAE4zgtYhQLAUZGyIkwSN7S55gdBCl2xaYKNxO8QLA81LThfhgwAdz4mi8nokwZC0LjsGo2jwMgl4pFkbDojBWBvHYQC8HYLgJKUwSrQhQZgAAegs2BWAAC2IOBRMQdhzigHEzjaSoAKA-iwGUoSswpAFyGNMTgQidlZLk98eLOKBbMQPAwHIAAheg+3YdhnK8wDgMkvyTPoQL5kpWYJlC+hxLZAkoq0qzYFErL3A0tzYsseLEuStKMqy9hxUQRAcp8-L-KtGRUVkiqqosOlaumbB6q-chAPKWhuHoSZWPIdz2oSpLUvSzLnNbMAoEG-hvLy4y3QCiatCmmZZq0OT5tgRb5hW9g1uDTaJnfEMFAuRhVghc5KiZVgQZiyj2qlTgoBjMAoVbcIhqugSbrG84HuqpQ5oW6yy0MuyLAa5zXIAQm0tqWD25Keuyi7ct80aiux0txNpSLnuxT9v1-Qy7uBgtSSwXTWH0wzXneeYzOAIA" rel="nofollow noreferrer">Playground link

class Dog {
    public dogName: string = ""
    public init(params: DogParams) { }
}
class Cat {
    public catName: string = ""
    public init(params: CatParams) { }
}
class DogParams { public dogValues: number = 0 }
class CatParams { public catValue: number = 0}

enum Kind {
    DogKind = 'DogKind',
    CatKind = 'CatKind',
}

const kindMap = {
    [Kind.DogKind]: Dog,
    [Kind.CatKind]: Cat,
};
type KindMap = typeof kindMap;

const paramsMap = {
    [Kind.DogKind]: DogParams,
    [Kind.CatKind]: CatParams,
}
type ParamsMap = typeof paramsMap;

type Tuples<T> = T extends Kind ? [T, InstanceType<KindMap[T]>, InstanceType<ParamsMap[T]>] : never;
type SingleKinds<K> = [K] extends (K extends Kind ? [K] : never) ? K : never;
type ClassType<A extends Kind> = Extract<Tuples<Kind>, [A, any, any]>[1];
type ParamsType<A extends Kind> = Extract<Tuples<Kind>, [A, any, any]>[2];

function getAnimalInstance<A extends Kind>(key:SingleKinds<A>, params: ParamsType<A>): ClassType<A> {
    const animalKlass: ClassType<A> = kindMap[key];

    const animalInstance = new animalKlass();

    animalInstance.init(params);
    return animalInstance;
}

// this works
const cat = getAnimalInstance(Kind.CatKind, new CatParams());

const shouldBeError = getAnimalInstance(Kind.DogKind, new CatParams()); // wrong params
const shouldBeErrorToo = getAnimalInstance(f(), new CatParams());       // undetermined kind
const shouldBeErrorAlso = getAnimalInstance(f(), new DogParams());      // undetermined kind

var k:Kind;
k = Kind.CatKind;

const suprisinglyACat = getAnimalInstance(k, new CatParams());    // even that works!
const shouldError = getAnimalInstance(k, new DogParams());

function f():Kind {
    return Kind.DogKind;
}

And another example of this written to mirror my other answer that required manual overloads. It also automatically gets Params types without needing separate manually defined map.

<a href="https://www.typescriptlang.org/play?ssl=1&ssc=1&pln=58&pc=1#code/MYGwhgzhAEAiD2BzACmATmAttA3tADgK4BGIAlsNAHYBc1hmxApmtALzQAMA3NAL4AoUJBgBhMABdUGbHiKkK1OhAloyVRO2gAiMNt6DhUaACFJ0rLgIlylWtGLx4IJmCpbVhJgYFDwxhE08dTIJAAp8OkCLTABKKz5+PxFocQkrEPDI1PN0LHi8RMN-GDN04KpQiLoymIL+JIEmKgZoAGl1ABMrQIAaHIl+ssbgeCoVaABrLoBZMHwtHAFoFegAbQ6qToA6QIBdKKRe5dWNru20g4Hj1fXNnbKrsoFE3wkAT3wmaAAVQnwXBAADxtLT3AB8YOgTAAHhJmp0YPdoAB+dYnFZtG6rACS4wkbmATB+nyYQLCHy+8AAZlNZvNYhs9uDsSs8SpCcTSeTKUwaXStnN8Iy2szoXCETAMbcMpUJHQwmA6OpqSxoMh4mxIW53g00choHQqEwAG4sAR7Q3UU0sbgCXnQADK6kQLnuwLakI4TPF8K2MDCoNhfsR7S6qLulqNNrQ8TRoOjZrQdodohKJK+IK90AAonCMMAJEC-gCmBB+ht+jqq1R3sy1gBGPYp0nqvKYCAZsmerR51RgQvF-6AitY6DV8e1+sAJmbvmphCohbIY3HIN9krDW3BYUmdGdGjdXQ9LIIdBine5ntidDTIi7Was0pN6Gg6ggNDvUAfPY4xoA7gKnRCmskxzrc77bJkESxLw0poEwEiEGg7jvrwMqrC8vgCAuS4SCu7jUmEN5bt0Sy3AhSEoaRFySHaggCC+rB7vcdqTGC5xpHaAhgIG5x9NagHRO2xGwdAAD04nQP+8BoJMEA8XxWy0YMglwEgMSibwknQmgaCyQ4TDAGAhAQN8mBkBAmCSMAAAWilEbE-QAepKAibEYkyjpLD6awzDGaZ3zTFs0CLp0iEsBZxqdA5xHOUwgFpJpHnobc3l6QZ-kmWZQGhVsEVoFFTAxbxjnjki-FHGpwkyFpGE6TJcnlg4hDpLZTDvP0oQAOQwO88DIdA1ImSA6TShhE2TVN9VSZ08AutAEjtdJ+kaNAxkTO1CHQNZLRgCAIDvIpkzxYluS1SlqzeWa7hLZZ0myfJx2na5yWeRJUluN0d0wD5sm+Dp-WENaxWLfAoU5bCA4SId0BjEF4aSOOi1kJg3wGaEum+QpTE7WQMLFXQ9y7Eg0AAD40WkWgtAd5WTu8dq48QWi8RZBOdC9NVYFpvi42zxXUu4HDETQxOBOTlNI1q9C05A9OM6+zMcKz+MC1QcXVRp7mwdhQA" rel="nofollow noreferrer">Playground link

class DogParam { public n: number = 0; }
class CatParam { public n: string = "a"; }
class BatParam { public n: boolean = true; }

class Dog { init(p: DogParam) { } }
class Cat { init(p: CatParam) { } }
class Bat { init(p: BatParam) { } }

enum Kind { Dog, Cat, Bat }

const kindMap = {
    [Kind.Dog]: Dog,
    [Kind.Cat]: Cat,
    [Kind.Bat]: Bat
}

type Tuples<K = Kind> = K extends Kind ? [
    K,
    InstanceType<(typeof kindMap)[K]>,
    InstanceType<(typeof kindMap)[K]> extends
        { init: (a: infer P) => any } ? P : never
] : never;
type SingleKinds<K> = [K] extends (K extends Kind ? [K] : never) ? K : never;
type ClassType<K> = Extract<Tuples, [K, any, any]>[1];
type ParamsType<K> = Extract<Tuples, [K, any, any]>[2];

function a<K extends Kind>(k: SingleKinds<K>, p: ParamsType<K>): ClassType<K> {
    var ins:ClassType<K> = new kindMap[k];
    ins.init(p);
    return ins;
}

function f(): Kind {
    return Kind.Cat;
}

var k:Kind;
k = Kind.Cat;

a(Kind.Dog, new DogParam()); // works
a(Kind.Cat, new DogParam()); // error because mismatch
a(f(), new DogParam());      // error because kind undetermined
a(f(), new CatParam());      // error because kind undetermined
a(f() as Kind.Dog, new DogParam());      // works, but hey, it's your fault
                                        // doing the wrong cast here manually
a(k, new CatParam());   // even this works
a(k, new DogParam());   // and this error

// you need to use exactly one kind at a time or it errors
var mixed: Kind.Dog | Kind.Cat = null as any;
var b = a(mixed, new DogParam());

var mixedfn = ():Kind.Dog | Kind.Cat => null as any;
var b = a(mixedfn(), new DogParam());

Solution that merges both my and Taytay ideas that generates everything it needs from "kinds to classes" map and uses automatically generated functions overload to provide nice intellisense <a href="https://www.typescriptlang.org/play?#code/MYGwhgzhAEAiD2BzaBvAUNT0AOBXARiAJbDQAmSAcmALYCmAXNBAC4BORAdsgLzQBE-DFjyES0LkRYAKbGDa0ITBIgAK8xQEpU0AL5p9oSDADCYFqmGZRxUsHPV6TVh27Q%20gqzgK2JnKbIaNErQZizqCsHaKHoGaEZQcEgRijo24hSIAGpgILh0IZy4NPh0bO7QAAyxCabmKcFpPuL2LDl5jNBFJWUVlfpodN3QANJcZJZYSYhjnBN8AOQqs2QLADReYSsVC1vj63Hx8Jys0ADW4wCyYNgV6FMA2isAdMvjALrKSBuPL3tzn1C5g2ugA3GgWABPbB0UZXG4VKEw%20AAM3O8Ow4Ih0NhABVcNgQAUADwjCorAB85OgdAAHiwhmQYNsAPzQB5eEZraBeACSJxYYE4wDouJxpIxT3eFO5fIFQpFYphxOkSLoqPRc2u2E0UqpdIZcxgXimMUkLCY0jATC4KN6qm0PCpQshemgbNU0CYnDoADcymh3l6un6yli1aFwFAlXRSVS%20ABRekKYAsYn4wkFblPbku3OcSHSh4ARne4IjDQgMbjFST7DAqfTBKJEGzXOgeY7BaLACYy2hsTDoABVfzHXHwfkMtgQOipojHYnD%20PQaTDmn0xkwF3u1dnJjDx1U33wIgTb2htjaA1b1fSfd%20O3lXlH6Ans-aNm84M%20-1sQewgAYsK6YVBmLYrqOC6cBOU5lLO86Ll4uIboaTLQOBBS7vedCQkwuIPJU7zctg%20EPH2r4EaWP6XmgFLgr68jQIgdAsAAgv4NC5PyrAKowwGkHwKK4MKLDQaSqG3pSOF4aMJFBEolbViMFKaAwJhRlW4oqZMWDAMcpxCkQXEgCMmkVBcWo3A8Zy4f2Xj6QKXbGdx8rCrCfA%20gA7s5JlmcY0iaFiUxGSZPGCu5zzmoEkQQEFA5TGwrG4GwnC%20a5vHueCAwAPQ5dAXnwGwZwQEcTmtBULHsZxGURSK0h-OYKzct5QLhApgXxWgeU0mwbBFaVjmnBAAAW8C4CAZAAEJ0AmfVFZVrEcS5IDhXx0gba%20LxvHMmiBS1dA%20WEladViaBAA" rel="nofollow noreferrer">Playground link

class Dog {
    public dogName: string = ""
    public init(params: DogParams) { }
}
class Cat {
    public catName: string = ""
    public init(params: CatParams) { }
}
class DogParams { public dogValues: number = 0 }
class CatParams { public catValue: number = 0}

enum Kind {
    DogKind = 'DogKind',
    CatKind = 'CatKind',
}

const kindMap = {
    [Kind.DogKind]: Dog,
    [Kind.CatKind]: Cat,
};
type KindMap = typeof kindMap;

type Tuples<K = Kind> = K extends Kind ? [
    K,
    InstanceType<KindMap[K]>,
    InstanceType<(typeof kindMap)[K]> extends
        { init: (a: infer P) => any } ? P : never
] : never;

type ClassType<K> = Extract<Tuples, [K, any, any]>[1];
type ParamsType<K> = Extract<Tuples, [K, any, any]>[2];

type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never
type Fnc<T = Tuples> = UnionToIntersection<
    T extends Tuples ? (key: T[0], p: T[2]) => T[1] : never
>;
var getAnimalInstance:Fnc = function<K extends Kind>(key: K, params:ParamsType<K>):ClassType<K> {
    const animalKlass = kindMap[key];

    const animalInstance = new animalKlass();

    animalInstance.init(params);

    return animalInstance;
}

// works
const cat = getAnimalInstance(Kind.CatKind, new CatParams());

// errors
const shouldBeError = getAnimalInstance((() => Kind.DogKind)(), new CatParams());

User Taytay who asked the question did an investigation of this code here <a href="https://www.typescriptlang.org/play?#code/PTAEHkCcEsHNoHYEMA2o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F-j66lmXFpmgkwTgloi55GQQZoAgF87m5QFonjHzyuj-TyjfiQhSC8w7BTDcieD-RyDSyEkoB5I3ZOAEg6okASAWrqbUCxgABWmAmI12WAypUI8M9hDBbh-4d4rhDpbJqhG0V5YgzBsYcwqA0AhgQwAktIhQz4Zh%20SR0AkLufMYm5J3BvB-BghohDxNoDIFgqgF01wxh%20JhprU8qySwS4wxhC%206AokHo0pc4ZqOqXuuY8wzZ%20AXq8SpBnxqqQwmAKAPAuuEmrpa6W23QcmiBggKhxQmw98owlqTFrEgwCUCiiGQAA" rel="nofollow noreferrer">Playground link to determine how it works.