I want to do something like this:
document("post").insert({ ... } /* TYPE SHOULD BE AUTOMATICALLY DETERMINED BY TYPESCRIPT */ );
The document()
function returns an object containing functions such as insert
, the object also contains a document
property which is assigned the value of the argument passed to document()
function. The object has a type of DocumentObject
and functions like insert
can access document
propery using this.document
. Everything is working fine but I want insert
to accept an argument of a certain type determined by the value of this.document
.
How can I have parameters that have types that vary based on the value of another variable. This is the declaration of insert
:
export default async function (this: DocumentObject, record: ???): Promise<...> {...}
The variable this.document
(which can be accessed from the function body) can contain the following values: post
, user
, comment
. I also have respective types for each possible value: Post
, User
, Comment
. This is howthis.document
is defined:
document: "post" | "comment" | "user" = ...;
My Question Is: How can I use Typescript to map each value to its respective type, so I can assign that type to record
parameter? Is this even possible in Typescript?
Note: Not a duplicate of Conditional parameter type based on another parameters’ value, and Conditional type based on the value of another key; They suggested I use function overloads, is there another way to do that?