1

I have an object (myObject) which contains properties that I am aware of upfront (id, isDisplayed) and properties which will be added in the future that I am not yet aware of - however I know they will be of type string (futureProperty1, futureProperty2). Is there a way to explicitly define the type of known properties and generalise the type of all the other properties of the same object (my assumption is to use the index signature). Example:

type KnownPropertyTypes = { id: number, isDisplayed: boolean };
type UnknownPropertyTypes = { [key: string]: string; }

type CustomType = KnownPropertyTypes & UnknownPropertyTypes;

const myObject: CustomType = { id: 1, isDisplayed: false }; // Error - Type '{ id: number; isDisplayed: false; }' is not assignable to type 'CustomType'.
myObject.futureProperty1 = 'value1';
myObject.futureProperty2 = 'value2';


const myObject2: CustomType = { id: 1, isDisplayed: false, futureProperty1: 'value', futureProperty2: 'value' }; // - Error - Type '{ id: number; isDisplayed: false; futureProperty1: string; futureProperty2: string; }' is not assignable to type 'CustomType'.

Playground example.

jcalz
  • 264,269
  • 27
  • 359
  • 360
Ovidijus Parsiunas
  • 2,512
  • 2
  • 8
  • 18
  • 1
    No, there is no specific type in TypeScript that works this way. See the answer to the linked question for more information. – jcalz Aug 21 '22 at 19:24

0 Answers0