From 0294c69a80b7f964aa66af142e3ce648b5ca0bae Mon Sep 17 00:00:00 2001 From: Tycho Grouwstra Date: Fri, 6 Oct 2017 22:34:36 +0800 Subject: [PATCH] add ObjectHasStringIndex --- src/object.d.ts | 12 +++--------- tests/object.test.ts | 12 ++++++++++++ 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/src/object.d.ts b/src/object.d.ts index b76cd26..ecb691d 100644 --- a/src/object.d.ts +++ b/src/object.d.ts @@ -52,13 +52,6 @@ export type IntersectionObjects = Pick>; export type ObjectValsToUnion = O[keyof O]; -export interface ObjectHasStringIndex { - (o: { [k: string]: any }): '1'; - (o: {}): '0'; -} -// type ObjectHasStringIndexTestT = ObjectHasStringIndex({ [k: string]: 123 }); // '1' -// type ObjectHasStringIndexTestF = ObjectHasStringIndex({ a: 123 }); // '0' - export type Simplify = Pick; export type Swap< @@ -70,9 +63,10 @@ export type Swap< // export type ObjectLength = ... // // check the length (number of keys) of a given heterogeneous object type. doable given `UnionLength` or (object iteration + `Inc`). +export type ObjectHasStringIndex = ({ 0: '0'; } & { [k: string]: '1'; })[UnionHasKey]; + // types not possible yet: -// `ObjectHasStringIndex`: accessing it works or throws, checking presence requires `ReturnType` to pattern-match and swallow these errors -// `ObjectHasNumberIndex`: ditto. +// `ObjectHasNumberIndex`: accessing it works or throws, checking presence requires `ReturnType` to pattern-match and swallow these errors // `ObjectNumberKeys`: a `number` variant of `keyof`. could be pulled off given union iteration (`Partial` -> iterate to filter / cast back to number literals)... but still hard to scale past natural numbers. // `ObjectSymbolKeys`: a `Symbol` variant of `keyof`. no clue how to go about this unless by checking a whitelisted set such as those found in standard library prototype. this feels sorta useless though. // `ObjectHasElem`: check whether a heterogeneous object type contains a given type among its elements. This could be done given `TypesEq`. diff --git a/tests/object.test.ts b/tests/object.test.ts index bda296e..df757da 100644 --- a/tests/object.test.ts +++ b/tests/object.test.ts @@ -426,6 +426,18 @@ describe(`object`, () => { }).expectToCompile(); }); + it(`the<'1', ObjectHasStringIndex<{ [k: string]: 123 }>>()`, () => { + tsst(() => { + the<'1', ObjectHasStringIndex<{ [k: string]: 123 }>>(); + }).expectToCompile(); + }); + + it(`the<'0', ObjectHasStringIndex<{ a: 123 }>>()`, () => { + tsst(() => { + the<'0', ObjectHasStringIndex<{ a: 123 }>>(); + }).expectToCompile(); + }); + }); });