代码之家  ›  专栏  ›  技术社区  ›  Coderama

在v-for指令中使用:key属性时,TS应出现类型错误

  •  0
  • Coderama  · 技术社区  · 2 年前

    正在尝试 maintain state with a key 对于 v-for 指令但typescript在 :key 属性

    TS错误

    (property) key?: string | number | symbol
    Type '{ toString: (radix?: number) => string; toFixed: (fractionDigits?: number) => string; toExponential: (fractionDigits?: number) => string; toPrecision: (precision?: number) => string; valueOf: () => number; toLocaleString: { ...; }; }' is not assignable to type 'string | number | symbol'.ts(2322)
    runtime-dom.d.ts(1480, 3): The expected type comes from property 'key' which is declared here on type 'ElementAttrs<LiHTMLAttributes>'
    

    密码

    <script lang="ts" setup>
      import { ref } from 'vue';
    
      interface Workspace {
        id: Number
        name: String
      }
    
      const workspaceList = ref<Workspace[]>([])
    </script>
    
    <template>
      <div>
        <ul>
          <li v-for="workspace in workspaceList" :key="workspace.id">
            {{ workspace.id }}: {{ workspace.name }}
          </li>
        </ul>
      </div>
    </template>
    
    1 回复  |  直到 2 年前
        1
  •  1
  •   jsejcksn    2 年前

    很可能您没有使用 Workspace 接口成员。您可能需要基本体,而不是它们的对象对应物(请注意小写):

    interface Workspace {
      id: number;
      name: string;
    }
    

    参考TS文档了解 everyday types :

    类型名称 String , Number Boolean (以大写字母开头)是合法的,但请参阅一些在代码中很少出现的特殊内置类型。 总是 使用 string , number boolean 对于类型。