【问题标题】:Typescript + Svelte - How to add types to spread component propsTypescript + Svelte - 如何添加类型以传播组件道具
【发布时间】:2021-12-24 16:24:24
【问题描述】:

是否可以使用由其他组件组成的组件来确保类型安全?

例如。如果我想构建具有特定验证的特殊类型的输入,等等应该扩展我的基本输入。

BaseInput.svelte

<script lang="ts">
  export let value = '';
  // + a lot more props
</script>

<input bind:value ... />

AgeInput.svelte - 这扩展了 BaseInput

<script lang="ts">
  import BaseInput from './BaseInput.svelte'

  export let {...inputProps}: /* Can we spread and infer BaseInput props? */;
</script>

<BaseInput {...inputProps} type="number" />

我们可以推断出BaseInput 属性吗?

【问题讨论】:

    标签: typescript svelte sveltekit


    【解决方案1】:

    Svelte 构建输入类型编号与类型文本不同。

    就我而言,我为 inport 构建了 2 种类型的输入。

    对于 inputText.svelte

    <script lang="ts">
      export enum TextType { text = "text", email = "email", password = "password" }
    
      export let id: string;
      export let type: TextType;
      export let label: string | null = null;
      export let placeholder: string | null = null;
      export let value: string | null = null;
    
      function typeAction(node: HTMLInputElement) {
        node.type = type
      }
    
    </script>
    
    <div class="textInput">
        <label class="textLabel" for={id}>{label}</label>
      <input on:input bind:value id={id} type="text" placeholder={ placeholder } use:typeAction />
    </div>
    

    这个函数:

     function typeAction(node: HTMLInputElement) {
        node.type = type
    

    传递输入类型非常重要:

      export enum TextType { text = "text", email = "email", password = "password" }
    

    这是我的 inputNumber.svelte 的一个例子:

    <script lang="ts">
        export let id: string;
        export let label: string | null = null;
        export let placeholder: string | null = null;
        export let value: number | null = null;
        export let min: number | null = null;
        export let max: number | null = null;
    </script>
      
    <div class="numberInput">
      <label class="numberLabel" for={id}>{label}</label>
      <input on:change bind:value id={id} type="number" placeholder={placeholder} min = {min} max = {max} {...$$restProps}/>
    </div>
    
    

    像往常一样导入之后。

    【讨论】:

    • 感谢您的详细解答!这就是我目前正在做的事情(忽略 svelte 不允许具有绑定值的动态类型的事实——我只是想提出一个简单的例子)。我要消除的是inputNumberinputText 都需要的重复道具
    猜你喜欢
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多