Useful utility functions and types for a more type-safe TypeScript
- types
Helper types to improve type-safety.
- classNames
Helper function to simplify type-safe interaction with classNames.
- validators
Validators to improve type-safety.
- isMathematicalNumber()
-
consider mathematical number if:
- typeof number
- can parse to int without need to remove anything (i.e. leading zeroes)
- can parse to float without need to remove anything
Helper types to improve type-safety.
-
types
-
~Prettify :
Prettify
-
~DeepRequired :
DeepRequired
-
~DeepPartial :
DeepPartial
-
~ValuesOf :
ValuesOf
-
~KeysOf :
KeysOf
-
~DeepKeysOf<TBase, :
DeepKeysOf
-
~PrefixedKeys<T, :
PrefixedKeys
-
~PartialBy<T, :
PartialBy
-
~RequiredBy<T, :
RequiredBy
-
~UndefinedToOptional :
UndefinedToOptional
-
~Prettify :
Helper type to show all properties of a complex base-type
Kind: inner typedef of types
Helper type to recursively remove all '?' and 'undefined' from all properties
Kind: inner typedef of types
Example
type Settings = {
org: string;
repo?: string;
owner?: {
profileUrl?: string;
contact: {
name: string;
mail: string;
} | undefined;
};
};
type ReqSettings = DeepRequired<Settings>;
// type ReqSettings = {
// org: string;
// repo: string;
// owner: {
// profileUrl: string;
// contact: {
// name: string;
// mail: string;
// };
// };
// }
Helper type to recursively make all child properties partial.
Kind: inner typedef of types
Example
type Foo = {
bar: string;
baz: {
foo: [
bam: string;
]
}
}
type Foo2 = DeepPartial<Foo>;
// type Foo2 = {
// bar?: string | undefined;
// baz?: {
// foo?: [bam?: string | undefined] | undefined;
// } | undefined;
// }
Helper type to generate values of a given type
NOTE: not for enum-types!
To create values of an enum-type, use:
type EnumVals = `${EnumType}`;
Kind: inner typedef of types
Example
const Foo = { A: "a", B: "b"} as const;
type FooVals = ValuesOf<typeof Foo>;
// type FooVals = "a" | "b"
// equivalent to: type FooVals = (typeof Foo)[keyof typeof Foo];
Helper type to generate keys of a given type
Kind: inner typedef of types
Example
const Foo = { A: "a", B: "b"};
type FooKeys = KeysOf<typeof Foo>;
// type FooKeys = "A" | "B"
// equivalent to: type FooKeys = keyof typeof Foo;
Helper type recursively generates a union type of all keys of a given type. The nested keys are prefixed by the parent property's key. Array elements are indexed.
Kind: inner typedef of types
Example
type Settings = {
org: string;
repo?: string;
owner?: {
profileUrl?: string;
contact: {
name: string;
mail: string;
} | undefined;
};
messages: {
title: string;
body: string;
}[];
};
type SettingKey = DeepKeysOf<Settings>;
// type SettingKey = "org" | "owner" | "owner.contact" | "owner.contact.name" | "owner.contact.mail" | "owner.profileUrl" | "repo" | "messages" | "messages[0]" | "messages[0].title" | "messages[0].body";
TypeScript Playground Link: https://www.typescriptlang.org/pt/play/?#code/KYDwDg9gTgLgBDAnmYcAixhgErAI4CuAllMACYA8AKgHxwC8cVcoMwAdmQM5wBiB7AMYwiEdgCg4cAPxNJcAFxMWINpx4BBKFACGiCkXYAzYFDgBVGvNlbd+jFlyES5CpatSlzVh25wIAEYAVsDC1nAA3nAA2gDScIZwANbAiBBGTAC6ALTSSg44+MSklAByYqUEADZVOgFVwNRxmTR0AL7yXgDc4uJIKOiYYLGpXADyRgASwFUoUNQAQjpcwAA0TAAKpEZEICpqflwwUIYA5gxwAESXdIwR8nEJ7Mmp6UxLKzl578vAzfu+HgACkMJjM5gAlNFMvIpLJzAD1P5gqEYLCpDJ0RiMQAfOAAAwAJBEqFtgDsQG1ifEAGRwI4ndinNr4rHYuB4okkskUqkRWn045nNrRYnsAgAWwCpjamVZ7PZeIKI0Q4ymMzmbnWXNJ212fIFDOFooi4qlMsyADp8R52UodTz9dS4HSjUyRWLJdKoLL5RivB8-rFMoi-IEQmEFdI2djOcTdeSnfyXYLGcy-QqpEqhiq1dNZqZFr9mtr447Kc7XUL3dbbdj7WW9RXk1W0yyeiKUmkMlRA5keuJQJBYAhkKhlaMJtRboMsLmJvnNQUnMVXLQaAP+qgAMrAGAiJk8O7yaCnJRu049KSkSDfC9X-wAd3Ypm+9wVYCg6SIDXMUCqd7VpebKCGIMA6MISjvpm7A6BKwDnkBD4KhKOg-ohabIRibQcnAAhkImL5kA+bQPvBXBcDopzAFwb6wiIMANBhZzIQEEBkIgzFMiR0IdpuY5wLu+5nCqFwTqqU5CQepxcBuvSgewRz0nu0kqgAjEoUkiakFyXBAz6mJaCngcIlqoT+lw9ApSkrMJTIqgATJpKnaYgunkZR1FcNEakOQAzFaDENJZQA
Helper type to generate prefixed keys of a given type
Kind: inner typedef of types
Example
const Foo = { A: "a", B: "b"};
type FooType = typeof Foo;
// type FooType = { "A": string; "B": string; }
type PrefixedFooKeys = PrefixedKeys<typeof Foo, 'foo.'>;
// type PrefixedFooKeys = { "foo.A": string; "foo.B": string; }
Helper type to make selected properties optional
Kind: inner typedef of types
Example
type Person = {
id: string;
name: string;
age: number;
};
type NewPerson = PartialBy<Person, 'id'>
// ^? type NewPerson = Omit<Person, "id"> & Partial<Pick<Person, "id">>
type PrettyNewPerson = Prettify<NewPerson>;
// ^? type PrettyNewPerson = { name: string; age: number; id? : string | undefined; }
Example
type NewPerson = PartialBy<Person, 'id' | 'age'>;
// ^? type NewPerson = Omit<Person, "id" | "age"> & Partial<Pick<Person, "id" | "age">>
Helper type to make selected properties required
Kind: inner typedef of types
Example
type Person = {
id?: string;
name?: string;
age?: number;
};
type NewPerson = RequiredBy<Person, 'id' | 'name'>
// ^? type NewPerson = Omit<Person, "id" | "name"> & Required<Pick<Person, "id" | "name">>
type PrettyNewPerson = Prettify<NewPerson>;
// ^? type PrettyNewPerson = { name: string; age: number; id? : string | undefined; }
Helper type to convert properties from potentially undefined to optional
Kind: inner typedef of types
Example
type Person = {
id: string | undefined;
name: string;
age: number | undefined;
};
type NewPerson = Prettify<UndefinedToOptional<Person>>
// ^? type NewPerson = { id?: string; name: string; age?: number; };
Helper function to simplify type-safe interaction with classNames.
Joins classes and avoids complicated checks and usage of nasty string-literals.
note: exported also as cns
-shorthand
Kind: inner method of classNames
Param | Description |
---|---|
...names | Array of |
Example
<div className={cns('primary', !isValid && 'disabled')} />
Validators to improve type-safety.
Checks if value is not null
and of object
-type.
Kind: inner method of validators
Param | Description |
---|---|
value | to check |
Returns true
if value is not undefined
and not null
.
Kind: inner method of validators
Param | Description |
---|---|
value | to check |
Checks existence of @propKey on an object and retypes the @obj
as an object having that property of unknown
-type.
Kind: inner method of validators
Param | Description |
---|---|
obj | to check |
propKey | which may or may not exist on the |
Checks existence of @propKeys on an object and retypes the @obj
as an object having these properties, all of which of unknown
-type.
Kind: inner method of validators
Param | Description |
---|---|
obj | to check |
propKeys | list of |
Checks if @obj is an array with at least one entry.
Kind: inner method of validators
Param | Description |
---|---|
obj | to check |
Checks if @obj is an array with zero entries.
Kind: inner method of validators
Param | Description |
---|---|
obj | to check |
Typeguard for enums-keys
note: not for number-enums
Kind: inner method of validators
Param | Description |
---|---|
enumType | the type to check against |
value | some value to check if it is a key of the given |
Example
enum MyEnum {
Thing1 = 'thing one',
Thing2 = 'thing two',
}
function onlyKeys(key: keyof typeof MyEnum) {
console.log(key, MyEnum[key]);
}
const testStr = "Thing2";
if (isEnumKey(MyEnum, testStr)) {
// compiler knows that testStr is of type `keyof typeof MyEnum`
onlyKeys(testStr);
}
Typeguard for enum values
note: not for number-enums
Kind: inner method of validators
Param | Description |
---|---|
enumType | the type to check against |
value | some value to check if it is a value of the given |
Example
enum MyEnum {
Thing1 = 'thing one',
Thing2 = 'thing two',
}
function onlyVals(val: MyEnum) {
console.log("onlyVals", val);
}
const testStr = "thing two";
if (isEnumValue(MyEnum, testStr)) {
// compiler knows that testStr is of type `MyEnum`
onlyVals(testStr);
}
consider mathematical number if:
- typeof number
- can parse to int without need to remove anything (i.e. leading zeroes)
- can parse to float without need to remove anything
Kind: global function
© 2024 Hans Krebs