【问题标题】:In typescript, can a generic function return an extended generic type?在打字稿中,泛型函数可以返回扩展的泛型类型吗?
【发布时间】:2021-10-04 23:19:49
【问题描述】:

我试图将类型检查添加到 const 对象并保持自动完成。

第一次尝试是 const foo:{[key:string]:string} = {bar:"foobar"}

检查类型,但结果类型不支持自动完成。 Screen cap from VS Code

然后我发现了这个问题提供的答案: Why autocomplete stop working in an object with type in TypeScript?

它使用返回原始类型的原始参数的函数。它很好用,但不是很通用。

export function asCSS<T extends { [key: string]: CSSProperties }>(arg: T): T {
  return arg
}

然后我尝试通过使用返回函数的函数使其通用。

function generateTypeCheck<T>(){
  return function asPropType<R extends { [key: string]: T }>(arg: R): R {
    return arg
  }
}

const foo = generateTypeCheck<string>()({bar:"foobar"}
Has type checking, auto complete, and is generic. But too clumsy

问题是当我尝试缩短它时,类型会消失。

export function checkType<T>(input) {
  return (generateTypeCheck<T>()(input))
}
Lost type checking and autocompletion when shorten

是否可以做类似最后一段代码的事情,但保留类型和自动完成?

【问题讨论】:

    标签: typescript typescript-typings typescript-generics


    【解决方案1】:

    不需要使用两个函数,使用两个泛型参数即可:

    function asPropType<T, R extends { [key: string]: T }>(arg: R): R {
        return arg
    }
    
    const foo = asPropType({ bar:"foobar" });
    foo.bar;
    

    Playground Link

    【讨论】:

    • 这将允许输入对象值的所有可能类型,例如const foo = asPropType({ bar: 'foobar', foo: 123 }) 我的意图是对对象属性进行类型检查,以便对象属性只能是指定的类型。跨度>
    猜你喜欢
    • 2020-06-29
    • 1970-01-01
    • 1970-01-01
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    相关资源
    最近更新 更多