简体   繁体   English

如何在 TypeScript 中键入普通 object

[英]How to type plain object in TypeScript

I wanna type a plain object of JavaScript, and write this:我想输入 JavaScript 的普通 object,然后写下:

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

But I found:但我发现:

type A = keyof PlainObject // string | number

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

type B = keyof PlainArray // number

Question 1: Why this happens?问题一:为什么会这样? Question 2: How can I type a plain object like { name: 'timi' }问题 2:我怎样才能输入一个普通的 object 像{ name: 'timi' }

This behavior is by design, the string index will mean the object is indexable by a string or a number .这种行为是设计使然, string索引意味着 object 可以通过stringnumber进行索引。 The docs say it best: 文档说得最好:

If you have a type with a string index signature, keyof T will be string | number如果您有一个带有字符串索引签名的类型, keyof T将是string | number 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])). string | number (不仅仅是字符串,因为在 JavaScript 中,您可以使用字符串(object['42'])或数字(object[42])来访问 object 属性)。 And T[string] is just the type of the index signature.而 T[string] 只是索引签名的类型。

There is no way to have a type for which keyof will return just string .没有办法让keyof只返回string的类型。 (There is the --keyofStringsOnly compiler option but that is there mostly for backward compatibility and should not be enabled on new code) (有--keyofStringsOnly编译器选项,但主要是为了向后兼容,不应在新代码上启用)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM