Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
542 views
in Technique[技术] by (71.8m points)

typescript - Tyepscript Error 2322 - Cannot init constant of generic type union of 2 optional index signatures

TypeScript Version: 4.1.3

Search Terms: Error 2322 Type is not assignable to type

Issue Type ElementShape has 2 index signature and both of them can be undefined - they have "?" before the ":"

Why I cannot initialize a constant of generic type ElementShape with only the common keys? Also Partial<ElementShape<A>> gave the same error.

Code

const element_def = {
    element1: {
        title: {}
    },
    element2: {
        price: {}
    }
} as const;

export type ElementName = 'element1' | 'element2';

export type CommonKeys = 'id' | 'active';

export type ElementShape<A extends ElementName> = 
   { [k in CommonKeys]?: string } &
   { [k in keyof typeof element_def[A]]?: number }


export function myFunc<A extends ElementName>(){

    let myconst:ElementShape<A> = {id: '', active: ''};
            // ~~~ Type '{ id: string; active: string; }' is not assignable to type 'ElementShape<A>'. Type '{ id: string; active: string; }' is not assignable to type '{ [k in keyof { readonly element1: { readonly title: {}; }; readonly element2: { readonly price: {}; }; }[A]]?: number | undefined; }'.

    let mypartial:Partial<ElementShape<A>> = {id: '', active: ''};
             // ~~~  Type '{ id: string; active: string; }' is not assignable to type 'Partial<ElementShape<A>>'.

    console.log(myconst, mypartial);

}
Compiler Options
{
  "compilerOptions": {
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictPropertyInitialization": true,
    "strictBindCallApply": true,
    "noImplicitThis": true,
    "noImplicitReturns": true,
    "alwaysStrict": true,
    "esModuleInterop": true,
    "declaration": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "moduleResolution": 2,
    "target": "ES2017",
    "jsx": "React",
    "module": "ESNext"
  }
}

Playground Link


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...