typescript中定义的索引签名为 string 类型,为什么使用时会变成 string | number 类型?

这是我的代码,vue3+typescipt

<script setup lang="ts">
interface NumberDictionary {
  [index: string]: string;
}

const formInfo: NumberDictionary = {
  name: "john",
  want: "eat",
};

Object.entries(formInfo).forEach(([key, value]) => {
  console.log(key, value);
});
</script>
<template>
  <form>
    <input v-for="(value, key) in formInfo" :name="key" :value="value" :key="key" type="text" />
  </form>
</template>

但是 typescript 推断的类型不一致
image.png

image.png

v-for 中遍历对象时,key被推断为string | number 类型,这就导致 input.name 无法接受 number 类型而类型报错。

有没有大佬能解释下。为什么key会被推断为 string | number 类型

阅读 2.1k
1 个回答

Vue3中,对象的 v-for 类型声明如下:

/**
 * v-for object
 */
export function renderList<T>(
  source: T,
  renderItem: <K extends keyof T>(
    value: T[K],
    key: K,
    index: number
  ) => VNodeChild
): VNodeChild[]

Typescript文档对于 keyof 的说明:

If the type has a string or number index signature, keyof will return those types instead:

type Arrayish = { [n: number]: unknown };
type A = keyof Arrayish; // number

type Mapish = { [k: string]: boolean };
type M = keyof Mapish; // string | number

Note that in this example, M is string | number — this is because JavaScript object keys are always coerced to a string, so obj[0] is always the same as obj["0"].

keyof types become especially useful when combined with mapped types, which we’ll learn more about later.

所以可以知道 key 的类型是 string | number

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Microsoft
子站问答
访问
宣传栏