Typescript optionally extending interface Typescript optionally extending interface javascript javascript

Typescript optionally extending interface


You can use type aliases along with an intersection on the Partial type:

type First = {    type1: string;    type2: string;}type Second = Partial<First> & {    type3: string;    type4: string;}


You can do this with interfaces using the Partial type.

interface First {    type1: string;    type2: string;}interface Second extends Partial<First> {    type3: string;    type4: string;}


You can also make all parts optional by providing an otherwise empty interface:

export interface ISingleScope {   scope: string;}export interface IMultiScope {   scopes: string[];   check?: boolean;}export interface IProvidedScope    extends Partial<ISingleScope>, Partial<IMultiScope> { }

However, usually this will require an explicit test of the used property exists, as at runtime neither of these information is present. So if your object comes with the name options than this would be sufficient:

if (options && options.scopes) {   // access properly 'IMultiScope'}