Reputation: 3436
Consider following interface/type:
interface Ifc {
fieldA: string;
fieldB: number;
}
I'd like to have a type assignable to non-object type variable, that tell TypeScritp following:
Hey TypeScript, this type is a single type from all types included in interface
Ifc
That gives me following way of controlling types:
// [[ ]] means placeholder
let oneFromIfc0: [[Type I can't figure out]] = 'Hey there' // It's ok, string is in Ifc type
let oneFromIfc1: [[Type I can't figure out]] = false // error, boolean does not conform to any field of Ifc
In case of object it wold be solved with mapped optional type:
type partialType = {
[k in keyof Ifc]?: Ifc[k];
}
That basically instructs TypeScritp to do following:
Hey TypeScript, take any field name of Ifc, make it optional. Then take this field type and copy it to this field.
But it have some flaws when compared to one i need:
o.fieldA
instead of fieldA
)Ifc
to new objectIfc
field nameUpvotes: 0
Views: 139
Reputation: 249706
If you want to get a union of all possible values in an interface you can use T[keyof T]
interface Ifc {
fieldA: string;
fieldB: number;
}
let oneFromIfc0: Ifc[keyof Ifc] = 'Hey there' // ok
let oneFromIfc1: Ifc[keyof Ifc] = false // err
Upvotes: 1