user10104341
user10104341

Reputation:

TYPESCRIPT - How to allow for more types in every property of a TypeScript object?

I have an object in my project. Here is the schema:

IObject : {
  prop1: number;
  prop2: number;
}

This is the typing I want for 90% of the usages. But a few instances require me to also return a string for every property. So, for a few instances I want an interface that returns:

object: IObjectWithStrings // Here I want to add string to each property as acceptable type.

// Something like
object: IObjects extends string

How do I do that?? I can create a new inteface just for that, but I would rather have the original interrface and extend it. Thank you!!

Upvotes: 1

Views: 53

Answers (2)

Roberto Zvjerković
Roberto Zvjerković

Reputation: 10127

You can just create another type from the one you have:

type IObject = {
    prop1: number;
    prop2: number;
}

type IObjectString = {
    [K in keyof IObject]: string 
}

type IObjectStringOrOriginal = {
    [K in keyof IObject]: string | IObject[K]
}

Upvotes: 1

leonardfactory
leonardfactory

Reputation: 3501

You can do this using generics. In this example, you can define a base type IObject<T>, where T represents the dynamic type, like this:

type IObject<T> = {
  prop1: T;
  prop2: T;
}

Than you can use directly IObject<number> or IObject<number | string>, where number | string means "prop1 is allowed to be one of both" (Union type), or you can just define additional types using the base type IObject<T>:

type IObjectNumber = IObject<number>;
type IObjectWithString = IObject<number | string>;

const objNum: IObjectNumber = { prop1: 10, prop2: 'abc' } // this will throw error
const objNumStr: IObjectWithString = { prop1: 10, prop2: 'abc' } // this will not throw error

Upvotes: 2

Related Questions