Typescript dynamic parameter interface does not compile without any

I have the following type, where if the name is something other than a "filter", the types "AggrEntry" and "filter" are of type "Aggr".

export interface Aggr {
    [name: string]: AggrEntry;
    filter?: Aggr;
}

However, the ts code will not compile unless I change [name: string]: AggrEntry;to [name: string]: any;.

Error

[ts] Property 'filter' of type 'ResponseAggregation' is not assignable to string index type 'ResponseAggregationEntry'.

Logically, I assume that typescript is trying to assign [name: string]for filtering, since the filter itself can be mapped to [name: string]. So, how would I structure my interface so that the ts compiler knows that the "name" will never "filter" then.

+4
source share
1 answer

, . :

export interface Aggr {
    [name: string]: AggrEntry |Aggr;
    filter?: Aggr;
}

, , , , filter Aggr.

- type :

export type Aggr  = {
    [name: string]: AggrEntry;
} & {
    filter?: Aggr;
}

let test : Aggr;
let foo = test.foo // foo is AggrEntry
test.filter // works, is of type Aggr

, , . filter . Object.assign :

let test : Aggr = Object.assign({
    foo: new AggrEntry()
}, {
    filter: {
        bar: new AggrEntry()
    }
});

, , Object.assign:

function createAggr(dynamicPart: {
    [name: string]: AggrEntry;
}, staticPart?: {
    filter?: Aggr;
}) {
    return Object.assign(dynamicPart, staticPart);
}

let test : Aggr = createAggr({
    foo: new AggrEntry()
}, {
    filter: {
        bar: new AggrEntry()
    }
});
+4

Source: https://habr.com/ru/post/1695699/


All Articles