Skip to content Skip to sidebar Skip to footer

How To Write Types / Or Use Use Types For Flatten Object Key In Typescript?

Consider this scenario interface abc { a: { b: string } } const test: abc = { a: { b: 'string'} } test['a.b'] = 'new string' // error type a.b doesnt exists https://codesandb

Solution 1:

What we'd like to see Typescript do here is convert one set of keys to another. There are ways it can do that, for instance with Pick:

interface IA {
    a: number;
    b: number;
    c: boolean;
}

constx: Pick<IA, 'a' | 'b'> = {
    a: 1,
    b: 2,
    c: 3, // type error here as we're not picking that property
}

In this example, Typescript is able to convert between the set of keys ['a', 'b', 'c'] and ['a', 'b'] based on selecting certain specified keys. We can also extend an object's keys:

type TestExtentionType = IA & { d: number };

consty: TestExtentionType = {
    a: 1,
    b: 2,
    c: true,
    d: 4,
}

What we'd need the type system to do though, in order to have typescript determine automatically the return types you're looking for, is to be able to go from key, key to 'key.key', or more generically, we need Typescript's type system to be able to concatenate string literals. At the point at which I'm writing this, it doesn't seem to be possible to have typescript do that.

The only option I can see to get close to what you need would be to define a specific type with your flattened key:

interface abc {
  a: { b: string }
}

interface abcFlattened {
    'a.b': string;
}

const flattenAbc = (x: abc): abcFlattened =>// do the flattening

Other options involve complete rewrites of what you're doing; if you want to get at that key as 'a.b' then I don't know as there's any other way of doing this.

Post a Comment for "How To Write Types / Or Use Use Types For Flatten Object Key In Typescript?"