簡體   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