Samantha J T Star
Samantha J T Star

Reputation: 32828

Why does typescript not check the naming for the contents of an array of objects?

I coded this interface:

interface IExamService {
    exam: IExam;
    exams: IExam[];
}  

interface IExam {
    current: boolean;
    id: number;
    name: string;
    subject: string;
}

and used it here:

class ExamService implements IExamService {

    exam: IExam;
    exams: IExam[] = [
        {
            current: false,
            id: 1,
            examId: 1,
            subject: 'x',
            name: 'Exam 1'
        },
        {
            current: false,
            id: 2322,
            examId: 2322,
            subject: 'y',
            name: 'Custom Exam 1'
        }
    ];
}

Can someone tell me why id does not flage the use of examId as an error?

Upvotes: 1

Views: 68

Answers (2)

bhspencer
bhspencer

Reputation: 13570

Typescript interfaces do not prevent you from adding additional properties. From the TypeScript Handbook:

Notice that our object actually has more properties than this, but the compiler only checks to that at least the ones required are present and match the types required. http://www.typescriptlang.org/Handbook#interfaces

Your object conforms to the interface IExam. Adding an additional property doesn't stop your object conforming to the interface.

Upvotes: 1

Mathieu Borderé
Mathieu Borderé

Reputation: 4367

just guessing here, wouldn't it only complain if you don't implement one of the properties of your interfaces ? Adding extra properties in addition to those defined by the interface doesn't look like a problem to me.

Upvotes: 1

Related Questions