How to declare, Two options for property declaration?

0

Issue

I have an interface like below

interface Student{
  Name: String;
  age: Number;
}

Instead of this I want to write like this

interface Student{
  Name: String;
  age | DOB: Number | Date;
}

ie the second property can either be age or DOB.
Is it possible? I am getting error for it.

Solution

interface StudentWithAge{
  name: String;
  age: Number;
  DOB?: never;
}

interface StudentWithDOB {
  name: String;
  DOB: Date;
  age?: never;
}

type Student = StudentWithAge | StudentWithDOB;

const student1: Student = {
    name: 'Humayun Kabir',
    age: 18
}

const student2: Student = {
    name: 'Humayun Kabir',
    DOB: new Date()
}

Answered By – Humayun Kabir

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More