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
>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.