Created
December 27, 2021 15:57
-
-
Save lordlycastle/741ec2f165982d86f789280d4f5becc9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as r from 'ramda'; | |
import * as fp from 'fp-ts'; | |
type PickStrings<T> = { | |
[Key in keyof T]: string extends T[Key] ? T[Key] : never | |
} | |
type StringKeysAsValues<T> = { | |
[Key in keyof T]-?: string extends T[Key] ? Key : never | |
} | |
type NonStringKeysAsValues<T> = { | |
[Key in keyof T]-?: string extends T[Key] ? never : Key | |
} | |
type StringKeys<T> = StringKeysAsValues<T>[keyof T]; | |
type NonStringKeys<T> = NonStringKeysAsValues<T>[keyof T]; | |
type PickStringsV2<T> = Omit<PickStrings<T>, NonStringKeys<T>> | |
type PickStringsV3<T> = Pick<T, StringKeys<T>> | |
type PickStringsExact<T> = { | |
[Key in StringKeys<T>]: T[Key] | |
}; | |
type O = { | |
a: string | null, | |
b?: string, | |
c: boolean | undefined, | |
d?: number | |
e: number | null, | |
} | |
type TestOptionalValue = O['d'] | |
type Equal<T, S> = T extends S ? S extends T ? true : never : never; | |
type EqualLiterals<T, S> = Equal<T[], S[]>; | |
const testEqual: EqualLiterals<'a' | 'b', StringKeys<O>> = true; | |
const testStringKeys: StringKeys<O> = 'a'; | |
type OStrings = PickStringsV2<O>; | |
type OStringKeys = keyof OStrings; | |
const osk: OStringKeys = 'a'; | |
const os: OStrings = { | |
a: null, | |
b: 'hello' | |
} | |
type OStringsKeysLength = Record<OStringKeys, number>; | |
const oskl: OStringsKeysLength = { | |
a: 1, | |
b: 2, | |
// c: 3, | |
} | |
const testIt = () => { | |
for (const key of r.keys(os)) { | |
const oldValue = os[key]; | |
if (oldValue !== undefined && oldValue !== null) | |
{ | |
const newValue = oldValue.padEnd(oskl[key], oskl[key].toString()); | |
console.log(newValue); | |
} else { | |
console.log(`key: ${key} is undefined`); | |
} | |
} | |
}; | |
export default testIt; | |
/** | |
* Returns an interface stripped of all keys that don't resolve to U, defaulting | |
* to a non-strict comparison of T[key] extends U. Setting B to true performs | |
* a strict type comparison of T[key] extends U & U extends T[key] | |
*/ | |
type KeysOfType<T, U, B = false> = { | |
[P in keyof T]: B extends true | |
? T[P] extends U | |
? (U extends T[P] | |
? P | |
: never) | |
: never | |
: T[P] extends U | |
? P | |
: never; | |
}[keyof T]; | |
type OKT = KeysOfType<O, string | null | undefined, false> | |
const okt: Record<OKT, number> = { | |
a: 1, | |
b: 2, | |
// c: 3, | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment