typescript - TS: Cum să faci ca tipul returnat să fie un tip al proprietății unui interface cu chei enum
Scopul meu este să creez o metodă set cu argumentele prop_key și prop_value care decid un tip de prop_value pe baza valorii unui prop_key.
Vreau să folosească enum ca nume de proprietăți și o interfață ca tipuri ale valorilor proprietăților.
Ce vreau să fac:
enum Property {
A = 0,
B,
C
}
interface PropertyStorage {
[Properties.A]: number;
[Properties.B]: string;
[Properties.C]: boolean;
}
setProperty(name: Property, value: TypeOfThisPropertyInStorage?): void
// Example
// setProterty(Propert.A, value => number)
// setProterty(Property.B, value => string)
// setProterty(Property.C, value => boolean)
Recent am încercat:
setProperty(name: Property, value: Pick<PropertyStorage , typeof name>): void
Dar când încerc să-l folosesc, primesc:
setProperty(Property.A, 15)
// Argument of type 'number' is not assignable to parameter of type 'Pick<PropertyStorage , Property>'.
Răspuns #1
Așa cum a menționat @captain-yossarian - soluția este
enum Property {
A = 0,
B,
C
}
interface PropertyStorage {
[Property.A]: number;
[Property.B]: string;
[Property.C]: boolean;
}
const setProperty = <Name extends keyof PropertyStorage>(name: Name, value: PropertyStorage[Name]) => {
}
setProperty(Property.A, 42)
