Home > Enterprise >  Typescript: How to use `extends` in certain circumstances
Typescript: How to use `extends` in certain circumstances

Time:01-14

I have two interfaces:

interface Person {
    name:string,
    active:boolean,
    id:number,
    location?:string
}

 interface Department {
    company:string,
    department:string
}

I use the Person interface once here:

const mycontact:Person = {
    name: 'John',
    active: true,
    id: 1
}

But in the same script I want to use both the Person and Department interface together but only here with the myPeeps variable. When I try to use the extends keyword I get an error: '?' expected Is it possible to only use extends in certain circumstances? If so how is that done?

const myPeeps:Person extends Department[] = [
    {name: 'A', active: true, id: 1, company:'', department: ''},
    {name: 'C', active: true, id: 2, company:'', department: ''},
    {name: 'D', active: true, id: 3, company:'', department: ''},
    {name: 'K', active: true, id: 4, company:'', department: ''},
    {name: 'T', active: true, id: 5, location: 'cali', company:'', department: ''}
]

CodePudding user response:

In this case use the & operator to satisfy both interfaces

const myPeeps: (Person & Department)[] = [
    {name: 'A', active: true, id: 1, company:'', department: ''},
    {name: 'C', active: true, id: 2, company:'', department: ''},
    {name: 'D', active: true, id: 3, company:'', department: ''},
    {name: 'K', active: true, id: 4, company:'', department: ''},
    {name: 'T', active: true, id: 5, location: 'cali', company:'', department: ''}
]

enter image description here

  • Related