javascript - Typescript pristup i dodjela svojstva objekta pomoću dinamičkog ključa


Pokušavam dodijeliti vrijednost iz objekta tipa TestInterface drugom objektu tipa TestInterface pristupajući mu putem dinamičkog ključa tipa keyof TestInterface. Međutim, TypeScript izgleda zaboravlja da je ovaj ključ isti na obje instance i stoga baca grešku.

Budući da je ova rečenica teška za čitanje, evo primjera:

interface TestInterface {
    testKey?: NestesOptInterface;
    optKey?: string;
}

interface NestesOptInterface {
    key1?: string;
    key2?: string
}

const myObj : TestInterface= {

}

const myObj2 : TestInterface = {
    testKey: {
        key1: "test",
    }
}

const attributes : string[] = ['testKey', 'optKey']

const myTestKey: keyof TestInterface = attributes[0] as keyof TestInterface

/**Type 'string | NestesOptInterface | undefined' is not assignable to type '(NestesOptInterface & string) | undefined'.
 * Type 'NestesOptInterface' is not assignable to type 'NestesOptInterface & string'.
 * Type 'NestesOptInterface' is not assignable to type 'string'.(2322)**/
myObj[myTestKey] = myObj2[myTestKey]

//does work (obviously)
myObj['testKey'] = myObj2['testKey']

Složeni dio je u tome što testKey u dodjeli myTestKey zapravo treba biti bilo koja vrijednost tipa string.

Pitao sam se je li ovo greška ili kako to mogu pravilno napraviti? Evo linka na Typescript Playground.

Odgovor #1

Uspio sam pronaći ne previše neuredno zaobilazno rješenje koje funkcionira za moj slučaj upotrebe. Pogledajte primjer u nastavku:

//solution
myObj = {
    ...myObj,
    [myTestKey]: myObj2[myTestKey]
}

Napomena: myObj je sada let umjesto const

Typescript Igralište

Odgovor #2

Trebaš dodati tip kao -

const myTestKey: keyof TestInterface = 'testKey';

Igralište

Povezani članci