Home > Software design >  How to override interface of an already instantiated object?
How to override interface of an already instantiated object?

Time:02-03

I have following @example/core package.

// @example/core

interface IExample {
  id: number;
}

const example: IExample = {
  id: 1
};

export { example, IExample }

In another @example/extension package I want to override interface of example const variable within the context of the entire package.

// @example/extension

import { example, IExample } from '@example/core';

declare module '@example/core' {
  interface IExample {
    name?: string;
  }
}

// this right now gives error `Property 'name' does not exist on type 'ITest'.`
console.log(example.name);

// however this works
const newExample: IExample = {
  id: 1,
  name: 'test',
};
console.log(newExample.name);

CodePudding user response:

An instance needs to be casted. It was assigned a type previously but the type has been overridden since.

If you move the interface overriding to before you instantiate example, it would work.

const myExample = example as IExample;
  • Related