可选属性的 Typescript 函数返回类型为 const,默认为 const

问题描述 投票:0回答:1

如果传递给函数,如何返回相同类型的参数,否则回退到另一个必需的参数?

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'})

返回的参数类型应该是一些字符串作为const,而不仅仅是字符串。该名称是可选的。如果存在 - name 属性的类型应该作为参数名称作为 const,否则作为资源作为 const

typescript typescript-typings typescript-generics
1个回答
1
投票

简单;只需允许

Name
默认为
R
:

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

请注意,

Name
现在在参数列表中排在第二位。那是因为可选参数不能出现在必需参数之前。

游乐场

© www.soinside.com 2019 - 2024. All rights reserved.