Home > Blockchain >  How to specify types on a Typescript object
How to specify types on a Typescript object

Time:02-20

Suppose I have a type and then I create an object with a value of this type e.g.

type MyType = {a: number, b: number, c: number}
const Defaults = {
    myDefault: {a: 5, b: 6, c: 7}
}

I want to be able to specify that Defaults.myDefault has type MyType. I found this answer, which tells me I can cast myDefault to MyType, but the problem is both

const Defaults = {myDefault: <MyType> {a: 5, b: 6, c: 7, d: 8}}

and

const Defaults = {myDefault: <MyType> {a: 5, b: 6}}

compile without error or even IDE warning, which kind of defeats the purpose. Basically what I want is the equivalent of

const Defaults : {myDefault: MyType} = {
    myDefault : {a: 5, b: 6, c: 7}
}

but being able to specify the MyType inside the object so that if I go on to add other defaults, I don't have to modify the code in two places:

// I don't want to go this way
export const Defaults : {myDefault: MyType, myOtherDefault: MyOtherType} = {
    myDefault : {a: 5, b: 6, c: 7}
    myOtherDefault : {d: 8, e: 9}
}

ON EDIT: Here's why I think this should be possible. If I make the defaults into functions, then it works; I can write:

const Defaults = {myDefault: () : MyType =>({a: 5, b: 6, c: 7})}

And now, if I either misspell something or leave off one of the properties, or add an extra one, I get a compile error. I guess I could just go this way, but why can't I just enforce a type on a non-functional property?

CodePudding user response:

What you're creating is an object in an object, so you need a type in a type:

type MyType = {a: number, b: number, c: number}

type DefaultType = {
  myDefault: MyType;
}

const Defaults: DefaultType = {
    myDefault : {a: 5, b: 6, c: 7}
}

Without being strict, there's little point in typing because you won't get type safety. However, you can extend the type by adding an optional Record<string, unknown>, which essentially means "...and other objects":

type DefaultType = {
  myDefault: MyType;
} & Record<string, unknown>

// then you can do
export const Defaults: DefaultType = {
    myDefault : {a: 5, b: 6, c: 7}
    myOtherDefault : {d: 8, e: 9}
  // another object here, and so on
}

CodePudding user response:

You can use the as assertion to do what you want:

type MyType = {a: number, b: number, c: number}


const Defaults = {myDefault: {a: 5, b: 6} as MyType}
  • Related