So I have a code like:
interface MyInterface{
a:any,
b:string,
c:boolean,
d:number,
readonly valueChanges:Subject<{key: keyof MyInterface, value: ???}>
}
where I dont know how to write the type of the value under the correct 'key'. I have tried the typeof MyInterface[key]
but probably this is not how to solve it. :(
Thanks for your time in advance!
You can make use of the AllValues
utility type posted by Titian Cernicova-Dragomir . Note that you do not need the extends Record<PropertyKey, PropertyKey>
as that is specific to the problem of inverting.
type AllValues<T> = {
[P in keyof T]: { key: P, value: T[P] }
}[keyof T]
You then apply this type to your interface, but make sure that {key: valueChanges...}
isn't one of your options.
type KeyValueObject = AllValues<Omit<MyInterface, "valueChanges">>
interface MyInterface{
a: any;
b: string;
c: boolean;
d: number;
readonly valueChanges: Subject<AllValues<Omit<MyInterface, "valueChanges">>>;
}
I don't like the circular referencing here, so personally I would break it into composable pieces. MyInterface
would end up as a type
rather than an interface
, but there is very little practical difference.
interface BaseInterface {
a: any;
b: string;
c: boolean;
d: number;
}
type WithValueChanges<T> = T & {
readonly valueChanges: Subject<AllValues<T>>
}
type MyInterface = WithValueChanges<BaseInterface>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.