我认为这可能是不可能的,因为即使是 native JSON.parse
的返回类型功能是 any
,但我一直在困惑如何在 TypeScript 中创建一个通用的 JSON 类型接口(interface)。有a solution on GitHub非常接近:
type JSONValue = boolean | number | string | JSONObject | JSONArray
interface JSONObject {
[k: string]: JSONValue
}
interface JSONArray extends Array<JSONValue> {}
const json: JSONObject = {}
console.log(json.gray[9])
...但无法在严格模式下编译:
~ ❯❯❯ tsc --strict test.ts
test.ts(11,13): error TS7017: Element implicitly has an 'any' type because type 'JSONValue' has no index signature.
我的理解是因为
JSONObject
和 JSONArray
有索引值,联合类型 JSONValue
也应该接受一个;显然编译器不同意。我很好奇我自己的启迪是否有办法解决这个问题;鉴于 GitHub 问题是从 2015 年开始的,也许 TypeScript 在此期间发生了变化。感谢经验丰富的脚本打字员的任何想法!
最佳答案
type JsonObject = { [key: string]: JsonValue };
type JsonValue =
| null
| boolean
| number
| string
| JsonValue[]
| JsonObject;
const stringify = (subject: JsonObject) => {};
stringify({
foo: 'bar',
});
stringify({
// @ts-expect-error
foo: () => {}
});
https://www.typescriptlang.org/play?ssl=20&ssc=4&pln=1&pc=1#code/C4TwDgpgBAUgzgewHYHkBGArCBjYUC8UA3lANoDWEIAXFHMAE4CWSA5gLq3zIBqAhgBsArtAC+AbgCwAKBmhIsREn7Do+GVCgAfKEiECBG7VDQIEAiHyRGdegLZoIDG3UYtWL7ssEjS7T0roWLhSstLYyPSuzGxMAGYgBFAAFHBCmDjAXIEZuACUBAB8xBIyMvQxrPEgyURGcWa0AORofAxNADQyonmh5W6xCbVGAPQjUAACwHAAtBAAHpC4cwwMCM7Smg0ItMkF+MVEot29QA
关于typescript - 在没有 "any."的 TypeScript 中创建 JSON 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46922993/