-
Notifications
You must be signed in to change notification settings - Fork 13k
Closed
Labels
DuplicateAn existing issue was already createdAn existing issue was already created
Description
Basically this would allow one to constrain the selection of keys, to belong to that of an existing type.
It is dependent on the following functionality not yet available yet, that has been proposal/requested:
- infer the spread operator. infer the spread operator function parameter names and types, via generic type extraction #25634, Tuples in rest parameters and spread expressions #24897
- infer with extends keyof constraint. infer the spread operator function parameter names and types, via generic type extraction #25634,
- recursive type evaluation.
KeyRef implementation
DropFirstParam<T> = T extends [ParamA : any, ...args : infer T] ? T : never
type KeysOfObjectRecusive<O extends {}, S extends any : []> S extends [infer K extends keyof O, ...args[]] ?
[K, keyof O[K] | undefined]
: [K, KeysOfObjectRecusive<O[K], DropFirstParam<S>>]
type KeysOfObject<S extends any : []> S extends [infer K extends keyof O, ... args : any []] ? [K, keyof O[K]] : [K]
function KeyRef<O extends {}, S extends KeysOfObjectRecusive<O,S>(object : O, K : S) : string []
{
const keys = string [];
let i = arguments.length - 1;
while(i--)
keys.push(arguments[i]);
return keys;
}
Examples of usage of keyRef:
KeyRef(object, 'KeyA', 'KeyAB','KeyABC') // valid
KeyRef(object, 'KeyB', 'KeyBC','KeyBCB') // valid
KeyRef(object, 'KeyC', 'KeyCC','KeyCCA')
KeyRef(object, 'KeyA', 'KeyBA','KeyBAC') // invalid
KeyRef(object, 'KeyB', 'KeyAB','KeyABC') // invalid
Templating the constraint as of 2018.07.12, results in error
// Error, Key A only refers to a type but is being used here as a value.
function KeyRef<O extends {}, KeyA extends keyof O, keyB extends O[KeyA]>(object : O, KeyA : KeyA, KeyB : KeyB) : string []
function KeyRef<O extends {}, KeyA extends keyof O>(object : O, K : KeyA) : string []
function KeyRef<O extends {}, S extends any>(object : O, Keys : any) : string []
Examples dependancies structure
const object = {
keyA : {
KeyAA : {
KeyAAA : 'AAA',
KeyAAB : 'AAB',
KeyAAC : 'AAC'
},
KeyAB : {
KeyABA : 'ABA',
KeyABB : 'ABB',
KeyABC : 'ABC'
},
KeyAC : {
KeyACA : 'ACA',
KeyACB : 'ACB',
KeyACC : 'ACC'
}
},
KeyB : {
KeyBA : {
KeyBAA : 'BAA',
KeyBAB : 'BAB',
KeyBAC : 'BAC'
},
KeyBB : {
KeyBBA : 'BBA',
KeyBBB : 'BBB',
KeyBBC : 'BBC'
},
KeyBC : {
KeyBCA : 'BCA',
KeyBCB : 'BCB',
KeyBCC : 'BCC'
}
}
,
KeyC :
{
KeyCA : {
KeyCAA : 'CAA',
KeyCAB : 'CAB',
KeyCAC : 'CAC'
},
KeyCB : {
KeyCBA : 'CBA',
KeyCBB : 'CBB',
KeyCBC : 'CBC'
},
KeyCC : {
KeyCCA : 'CCA',
KeyCCB : 'CCB',
KeyCCC : 'CCC'
}
}
}
Metadata
Metadata
Assignees
Labels
DuplicateAn existing issue was already createdAn existing issue was already created