gpt4 book ai didi

javascript - 如何在 TypeScript 中输入普通对象

转载 作者:行者123 更新时间:2023-11-28 03:32:58 25 4
gpt4 key购买 nike

我想输入一个普通的 JavaScript 对象,然后写下:

interface PlainObject {
[k: string]: any;
}

但我发现:

type A = keyof PlainObject // string | number

interface PlainArray {
[k: number]: any;
}

type B = keyof PlainArray // number

问题1:为什么会出现这种情况?问题 2:如何输入像 { name: 'timi' }

这样的普通对象

最佳答案

此行为是设计使然,字符串索引意味着该对象可以通过字符串数字进行索引。 docs说得最好:

If you have a type with a string index signature, keyof T will be string | number (and not just string, since in JavaScript you can access an object property either by using strings (object['42']) or numbers (object[42])). And T[string] is just the type of the index signature.

没有办法让 keyof 只返回 string 的类型。 (有 --keyofStringsOnly compiler option 但这主要是为了向后兼容,不应在新代码上启用)

关于javascript - 如何在 TypeScript 中输入普通对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58003204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com