- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是我在 Stack Overflow 上的第一篇文章,所以我会尽力解释!我有这个名为 phrases.JSON 的 JSON 文件:
{
"start": {
"affirmative": [
some strings
],
"interrogative": [
some strings
]
},
"mid": [
some strings
]
}
所以我将它作为短语导入到另一个文件中,使用 import phrases from '../utils/phrases.json'
,并在 modules.d.ts 中声明。
declare module '*.json' {
const data: any
export default data
}
我在导入phrases.json的文件中做了一个接口(interface),就这样:
interface Phrases {
[key: string]: TypePhrases | string[]
start: TypePhrases
mid: string[]
}
interface TypePhrases {
[key: string]: string[]
affirmative: string[]
interrogative: string[]
}
在我的课上,我创建了一个函数:
private getPhrases(position: string | number) {
return phrases[position]
}
所以如果我在我的类中调用这个函数,如果我给字符串'start'我想得到起始对象,或者如果我给'mid'我想得到字符串数组,就像这样:
const MID_STRING: string = 'mid'
console.log(this.getPhrases(MID_STRING)[0])
但是在我的返回函数中,我得到了这个错误:
Element implicitly has an 'any' type because expression of type 'string | number' can't be used to index type '{ "start": { "affirmative": string[]; "interrogative": string[]; }; "mid": string[]; }'. No index signature with a parameter of type 'string' was found on type '{ "start": { "affirmative": string[]; "interrogative": string[]; }; "mid": string[]; }'.
你能帮帮我吗?我尝试了很多东西,我不知道如何解决...谢谢!
最佳答案
导入对象的类型将由 .json
文件中的对象决定,而不是由您定义的类型决定(我看不到两者之间的联系)。此外,定义 declare module '*.json'
不是编译器使用的定义,因为它在磁盘上找到文件。
不过你遇到的问题其实很简单。 Typescript 无法证明 phrase
是索引 phrases
的有效键。
您可以使用类型断言来实际使用您定义的类型:
private getPhrases(position: string) {
return (phrases as Phrases)[position]
}
m() {
const MID_STRING = 'mid'
var a = this.getPhrases(MID_STRING); // a is TypePhrases | string[]
if (a instanceof Array) { // must use type guard to index
a[0]
}
}
您还可以采取更安全的选择,使用 keyof
结合泛型来实际获取对象中值的正确类型。这只有在您通常使用常量时才有可能。
private getPhrases<K extends keyof typeof phrases>(position: K) {
return phrases[position]
}
m() {
const MID_STRING = 'mid' // no string annotation, MID_STRING is typed as 'mid'
this.getPhrases(MID_STRING)[0]; // ts knows this returns string[] and we can index iderctly into it
}
如果你有一个 string
想用来索引一个类型,你也可以断言该字符串是一个 keyof
类型。这当然不是类型安全的,但有时是必要的:
private getPhrases(position: string) {
return phrases[position as keyof typeof phrases]
}
关于typescript - 元素隐式具有 'any' 类型,因为类型字符串的表达式 |数字不能用于索引类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57409041/
我是一名优秀的程序员,十分优秀!