Imagine the following interface/type:
interface Ifc {
fieldA: string;
fieldB: number;
}
I'm looking for a type that can be assigned to a non-object type variable in TypeScript, indicating the following:
Hello TypeScript, this type is a single type from all types included in the interface
Ifc
This allows me to control types in the following way:
// [[ ]] represents a placeholder
let oneFromIfc0: [[Type I can't figure out]] = 'Hey there' // This is fine, as string is part of the Ifc type
let oneFromIfc1: [[Type I can't figure out]] = false // error, since boolean does not match any field in Ifc
In the case of an object, it could be solved with a mapped optional type:
type partialType = {
[k in keyof Ifc]?: Ifc[k];
}
This essentially tells TypeScript to do the following:
Hello TypeScript, make each field in Ifc optional. Then copy the type of that field to this new field.
However, this approach has some drawbacks when compared to the one I need:
- Requires interaction with objects rather than scalar values (using
o.fieldA
instead offieldA
) - Allows mapping multiple fields of Ifc to the new object
- The field name must match consistently with Ifc field names