Proste ćwiczenie, poznajemy dalej TypeScripta i powoli zabieramy się do napisania aplikacji quizowej w TS. Do dzieła.

Ok, krok pierwszy:

type Question =  {
    question: string;
};

let q1: Question = {
    question: "What is 2 + 2",
}

Problem – pytanie nie ma znaku zapytania. Coś możemy na to poradzić? Możemy!

type Question =  {
    question: `${string}?`;
};

let q1: Question = {
    question: "What is 2 + 2",
}

//Type '"What is 2 + 2"' is not assignable to type '`${string}?`'.ts(2322)

Ok, wstawmy ten znak zapytania:

type Question =  {
    question: `${string}?`;
};

let q1: Question = {
    question: "What is 2 + 2?",
}

Teraz odpowiedzi… Niech będzie abcd na razie:


type Question =  {
    question: `${string}?`;
    answers: {
        a: string,
        b: string, 
        c: string,
        d: string,
    }
};

let q1: Question = {
    question: "What is 2 + 2?",
    answers: {
                a: "4",
                b: "5",
                c: "6",
                d: "8"
            },
}

Dobra, uprośćmy to sobie:

type Question =  {
    question: `${string}?`;
    answers: {
        [P in "a"|"b"|"c"|"d"]: string
    }
};

let q1: Question = {
    question: "What is 2 + 2?",
    answers: {
                a: "4",
                b: "5",
                c: "6",
                d: "8"
            },
}

Ok, teraz odpowiedzi. Przyda się operator keyof:

type Question =  {
    question: `${string}?`;
    answers: {
        [P in "a"|"b"|"c"|"d"]: string
    },
    correctAnswer: keyof Question["answers"]
};

let q1: Question = {
    question: "What is 2 + 2?",
    answers: {
                a: "4",
                b: "5",
                c: "6",
                d: "8"
            },
    correctAnswer: "a"
}

Ok, teraz sobie ulepszymy:

type Question<K extends string> =  {
    question: `${string}?`;
    answers: {
        [P in K]: string
    },
    correctAnswer: K
};

Teraz specjalnie zróbmy 3 błędy:

let q1: Question<"a"|"b"|"c"|"d"|2> = {
    question: "What is 2 + 2?",
    answers: {
                a: "4",
                b: "5",
                c: "6",
                d: "8",
                e: "10"
            },
    correctAnswer: "e"
}

Mamy zły typ, mogą być tylko stringi, podkreśla nam e oraz correct answer. To teraz zróbmy dobrze:

let q1: Question<"a"|"b"|"c"|"d"> = {
    question: "What is 2 + 2?",
    answers: {
                a: "4",
                b: "5",
                c: "6",
                d: "8",
            },
    correctAnswer: "a"
};

Ok, to by było na tyle, więcej TSa niedługo…