繁体   English   中英

检查泛型函数参数中的类型并返回此参数的对象字面量类型

[英]Check types in argument of generic function and return object literal type of this argument

我的任务

我有两个接口。

interface ComponentOptions<Props> {
  abstract?: boolean;
  functional: boolean;
  props?: Props;
  name?: string;
  render?(props: Props): boolean;
}

interface ComponentProps {
  title: string;
  dark: boolean;
}

我需要实现一个功能

  • 需要一个接口来替代Props泛型类型
  • 执行与函数参数对象中的Props类型相关的任何检查
  • 根据传递的参数对象返回对象文字类型
    • 不返回ComponentOptions<Props>接口

strict: true需要strict: true编译器选项。

实际解决方案

我已经实现了接收两个参数的createComponent函数:

  • 必需的options对象文字
  • props ,被视为类型转换的虚构参数
function createComponent<
  Props,
  Options extends ComponentOptions<Props>
>(options: Options, props: Props): Options {
  props;
  return options;
}

我通过这样的认识达到了预期的结果。 但我真的不喜欢它。

const component = createComponent({
  abstract: true,
  functional: true
}, {})

const componentWithProps = createComponent({
  functional: false,
  name: 'bar',
  props: {
    title: 'bar',
    dark: true
  },
  render(props) {
    return props.dark
  }
}, {} as ComponentProps)

问题

我想摆脱props参数只剩下options ,并使用通用参数设置 props 的类型,而不是强制转换props参数。

它可能看起来像这样:

const component = createComponent<ComponentProps>({
  functional: true,
  props: { // Check 'title' and 'dark' types
    title: 'comp',
    dark: true
  },
  render(props) { // Pass type for the props
    return props.dark;
  }
})

// When we hover on `component` variable,
// display all defined properties in the `options`
{
  functional: true,
  props: ComponentProps,
  render(props: ComponentProps): boolean
}

如何实现这一目标?

链接到游乐场

我用这个解决方案解决了我的问题:

interface FunctionalComponent<Props> {
  <Options extends ComponentOptions<Props>>(opts: Options): Options
}

function createFunctionalComponent<Props = {}>() {
  return (o => o) as FunctionalComponent<Props>;
}

const component3 = createFunctionalComponent<ComponentProps>()({
  functional: false,
  name: 'bar',
  props: {
    title: 'bar',
    dark: true
  },
  render(props) {
    return props.dark
  }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM