You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
While digging into the keyofStringsOnly flag, I realized the following.
Code
Let's say we have this object literal:
constobj={a: 1,b: true,c: "yo",};
It has a finite number of possible keys/values/entries. In many cases, this is true for non-literals as well:
interfaceObj{a: 1;b: true;c: "yo";}declarefunctiongetObj(): Obj;// we can be certain that `obj` will have the `Obj` signatureconstobj=getObj();
Let's try to get the key, value and entry types from obj.
// expected signature of `[string, 1 | true | "yo"][]`// actual signature of `[string, string | number | boolean][]`constentries=Object.entries(obj);// expected signature of `"a" | "b" | "c"`// actual signature of `"a" | "b" | "c"`typeKeyOfType=keyoftypeofobj;// expected signature of `{ a: 1; b: true; c: "yo"; }`// actual signature of `{ a: number; b: boolean; c: string; }`typeObjType=typeofobj;// expected signature of `1 | true | "yo"`// actual signature of `string | number | boolean`typeValueType=ObjType[KeyOfType];
I've played around with my TSConfig to see if I can get the correct behavior. keyofStringsOnly nor strictMode make a difference.
In discussions such as #35745, some users state that it's a 3rd-party library's responsibility to correct this (IMO seemingly-faulty) inference. A custom entries function––for example––could make use of the Exclude utility type. While getting the correct signature is certainly possible in the language, I believe it should––in the cases above––be the default.
Please let me know if I'm missing something, or haven't the right configuration. Any help would be greatly appreciated. Thank you!
Search Terms: "infer", "object", "literal", "key", "value", "entry", "entries", "type", "signature", "keyof"
While digging into the
keyofStringsOnly
flag, I realized the following.Code
Let's say we have this object literal:
It has a finite number of possible keys/values/entries. In many cases, this is true for non-literals as well:
Let's try to get the key, value and entry types from
obj
.I've played around with my TSConfig to see if I can get the correct behavior.
keyofStringsOnly
norstrictMode
make a difference.In discussions such as #35745, some users state that it's a 3rd-party library's responsibility to correct this (IMO seemingly-faulty) inference. A custom
entries
function––for example––could make use of theExclude
utility type. While getting the correct signature is certainly possible in the language, I believe it should––in the cases above––be the default.Please let me know if I'm missing something, or haven't the right configuration. Any help would be greatly appreciated. Thank you!
Playground Link:
here
The text was updated successfully, but these errors were encountered: