Home > OS >  Typescript: How do define keys of an object by inference?
Typescript: How do define keys of an object by inference?

Time:09-28

I'd like to define the keys of the nested object without typing it out. How can I get typescript to only accept the keys "itemA" and "itemB" without typing it out (because in practice there are more than 2 keys)?

// I don't want the key to be any string. It should be whatever is in the object so `itemA | itemB`.
// I also DO NOT want to define all keys myself since it's much longer than in this example
interface IMyObject {
    bucket1: Record<string, string>;
}

const myObject:IMyObject = {
    bucket1: {
        itemA: "itemA",
        itemB: "itemB",
    },
}

// This should be invalid
const itemC = myObject.bucket1.itemC;

CodePudding user response:

This should do the job

// I don't want the key to be any string. It should be whatever is in the object so `itemA | itemB`.
// I also DO NOT want to define all keys myself since it's much longer than in this example
interface IMyObject<T> {
    bucket1: Record<keyof T, string>;
}

const bucket = {
        itemA: "itemA",
        itemB: "itemB",
    }
    
const myObject:IMyObject<typeof bucket> = {
    bucket1: bucket,
}

// This should be invalid
const itemC = myObject.bucket1.itemC;

CodePudding user response:

To answer the question as asked, you do not need any explicit types at all. TypeScript will infer the type information based on the object literal:

const myObject = {
    bucket1: {
        itemA: "itemA",
        itemB: "itemB",
    },
}

// This is invalid
const itemC = myObject.bucket1.itemC;

If your situation is more complex, then please provide additional details to help us understand what exactly you are trying to do.

  • Related