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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…