Let say there is a type A and which will be a type of object property objA
:
type A = {
a: number
}
I would like to have an object to have objA
and other properties will be expected to be type string
.
However, the following using Index Signatures will make the value has more types.
type B = {
objA: A;
[index: string]: string | A; // cannot be `string` here or it will error
}
const b: B = {
objA: {
a: 1
},
someText: `some string`,
}
b.someText // expect `someText` to be string, but got `string | A`
// ^?
But the above can resolve objA
correctly.
Please notice that const b
have to be discourage excess properties
during direct defining object, but may or may not for object references. Or in other words, it need to be Stricter object literal assignment checks:
const b: B = {
objA: {
a: 1,
b: 2, // <-- does get error.
},
someText: `some string`,
}
Following is acceptable.
const objA = { a: 1, b: 2 }
const b: B = {
objA, // <-- object reference which cannot forbid excess properties maybe allowed. No error here.
someText: `some string`,
}
Below were other attempts.
type C = {
[a in Exclude<string, "objA">]: string;
}
const c: C = {
objA: { // error: Type '{ a: number; }' is not assignable to type 'string'.(2322)
a: 1
},
someText: `some string`,
}
type E = {
[a in Exclude<string, "objA">]: string
} & {
objA: A,
default: string,
}
// Error:
// Type '{ objA: { a: number; }; someText: string; }' is not assignable to type 'E'.
// Type '{ objA: { a: number; }; someText: string; }' is not assignable to type '{ [x: string]: string; }'.
// Property 'objA' is incompatible with index signature.
// Type '{ a: number; }' is not assignable to type 'string'.(2322)
const e: E = {
objA: {
a: 1
},
someText: `some string`,
}
Any ideas?