我不是在那里正在掌握打字稿,并处于倒下的情况。
目标:在单页上基于quizId输出测验,quizId是下面JSON中的起始编号。
预期和实际结果:预期的结果是能够从包含所有带问答题的JSON文件的quizId中获取单个测验。
实际结果从我的代码中引发类型错误。
错误消息:元素隐式地具有“ any”类型,因为类型“ string”的表达式不能用于索引类型
尝试以下内容:下面是界面:
export interface Question {
id: number;
answer: string;
correct: boolean;
}
export interface Questions {
questionId: number;
question: string;
answers: [Question];
}
export interface Quiz {
url: string;
name: string;
description: string;
questions: [Questions];
}
我的代码:
<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator';
import { QuizIndex } from '@/models/quiz.interface';
import MultiQuizQuestion from '@/components/multi-quiz-question.json';
@Component({})
export default class QuizPage extends Vue {
@Prop() public quizIndex!: QuizIndex;
// quizId!: number;
private multiQuizQuestions = MultiQuizQuestion;
private quizUrl: string = '';
private quizId!: number;
private created() {
this.quizUrl = this.$route.params.id;
}
private get currentQuiz() {
this.quizId = Object.values(this.multiQuizQuestions).findIndex(object => object.url == this.quizUrl);
console.log(this.multiQuizQuestions[this.quizId]); // <-- This brings me the error
return '';
}
};
</script>
我有一个JSON文件,其中可以查询问题和答案。具有以下结构。
{
"1": {
"url": "car-quiz",
"name": "Car Quiz",
"description": "This is a quiz about cars",
"questions": [
{
"questionId": 1,
"question": "What car is the best",
"answers": [
{
"id": 1,
"answer": "Toyota,
"correct": false
},
{
"id": 2,
"answer": "Ferrari",
"correct": true
}
]
},
{
"questionId": 2,
"question": "What car does James Bond like",
"answers": [
{
"id": 1,
"answer": "Nissan",
"correct": false
},
{
"id": 2,
"answer": "Aston Martin",
"correct": true
},
]
},
]
},
"2": {
"url": "hockey-quiz",
"name": "Hockey Quiz",
"questions": [
{
"questionId": 1,
"question": "What does NHL stand for?",
"answers": [
{
"id": 1,
"answer": "National Hockey Leauge",
"correct": true
},
{
"id": 2,
"answer": "National Horse Leauge",
"correct": false
},
]
},
]
}
}
摘要:我不确定如何通过JSON中的“没有名称”键在此处使用接口,然后将其引用到测验中,如下所示:
export interface QuizIndex {
quizId: [Quiz];
}
我知道this.multiQuizQuestions[this.quizId]
中的quizId输入不正确,但是我无法弄清楚应该如何完成。我想学习此方法,而不是使用快捷方式打开"noImplicitAny": false
这不是测验的数组,它是测验的索引对象,带有记录<>
export type QuizIndex = Record<string, Quiz>;
或带有索引签名
export interface QuizIndex {
{[key: string]: Quiz};
}