Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript function return type of the optional property as const with default

How to return the same type of the parameter if passed to the function, else fallback to another required parameter?

const r = <Name extends string, R extends string>({
   name,
   resource
}: {
    name?: Name,
    resource: R
}) => {

   return {
// here the type of the "name" should be same as the Name if exist, else as R. As const
       name: (name || resource) as Name extends never ? R : Name,
       resource: resource
   }
}

// this way works. The returned type is {resource: "test", name: "test-name"}
const resource = r({resource: 'test', name: 'test-name'})

// But this way the returned type is {name: string, resource: 'test'}. 
// The type of "name" should be "test" since the name parameter is missing, but it returns string instead
const resource = r({resource: 'test'})

The returned parameter types should be some string as const, not only string. The name is optional. If exist – the type of the name property should be as the argument name as const, otherwise as resource as const

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Simple; just allow Name to default to R:

const r = <R extends string, Name extends string = R>({
    name,
    resource,
}: {
    name?: Name;
    resource: R;
}) => {
    return {
        name: (name || resource) as Name,
        resource: resource,
    };
};

Note that Name is now second in the parameter list. That is because optional parameters cannot come before required ones.

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading