Skip to content

Commit

Permalink
feat: add explicit return type for all public function
Browse files Browse the repository at this point in the history
  • Loading branch information
GreatAuk committed Mar 6, 2024
1 parent 4f87c65 commit 9915cf4
Show file tree
Hide file tree
Showing 49 changed files with 97 additions and 62 deletions.
2 changes: 1 addition & 1 deletion packages/cli/src/getGitCommitHash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { execSync } from 'node:child_process'
* return the current commit hash
* @returns The git commit hash
*/
export function getGitCommitHash() {
export function getGitCommitHash(): string | undefined {
try {
const hash = execSync('git rev-parse --short HEAD').toString().replace('\n', '').trim()
if (hash === 'undefined')
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/getHostProjectPkgVersion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@
* It returns the version of the host project's package.json file
* @returns version
*/
export function getHostProjectPkgVersion() {
export function getHostProjectPkgVersion(): string {
return process.env.npm_package_version as string
}
2 changes: 1 addition & 1 deletion packages/cli/src/isDirector.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import fs from 'node:fs/promises'

export async function isDirector(path: string) {
export async function isDirector(path: string): Promise<boolean> {
try {
const stat = await fs.stat(path)
return stat.isDirectory()
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/isFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import fs from 'node:fs/promises'
* @param {string} path - The path to the file to check.
* @returns A boolean value.
*/
export async function isFile(path: string) {
export async function isFile(path: string): Promise<boolean> {
try {
const stat = await fs.stat(path)
return stat.isFile()
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/pathExists.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { access } from 'node:fs/promises'
* @param {string} path - The path to check.
* @returns A promise that resolves to a boolean.
*/
export async function pathExists(path: string) {
export async function pathExists(path: string): Promise<boolean> {
try {
await access(path)
return true
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/callLimit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { isFunction, isNumber } from '@utopia-utils/share'
* ```
* @linkcode https://github.com/GreatAuk/utopia-utils/blob/main/packages/core/src/callLimit.ts
*/
export function callLimit<T extends (...args: any[]) => any>(fn: T, limit = 1) {
export function callLimit<T extends (...args: any[]) => any>(fn: T, limit = 1): (this: ThisParameterType<T>, ...args: Parameters<T>) => ReturnType<T> {
if (!isFunction(fn))
throw new TypeError('fn expected a function')

Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/capitalize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@
* @returns {string} - The capitalized string.
* @linkcode https://github.com/GreatAuk/utopia-utils/blob/main/packages/core/src/capitalize.ts
*/
export function capitalize<T extends string>(str: T) {
export function capitalize<T extends string>(str: T): Capitalize<T> {
return str.charAt(0).toUpperCase() + str.slice(1) as Capitalize<T>
}
2 changes: 1 addition & 1 deletion packages/core/src/createEnumFromOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
* ```
* @linkcode https://github.com/GreatAuk/utopia-utils/blob/main/packages/core/src/createEnumFromOptions.ts
*/
export function createEnumFromOptions<T extends readonly Option[]>(options: T) {
export function createEnumFromOptions<T extends readonly Option[]>(options: T): MapTuple<T> {
const res: Record<string, unknown> = {}
try {
options.forEach((v) => {
Expand Down
6 changes: 3 additions & 3 deletions packages/core/src/csv.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { isArray, isPlainObject } from '@utopia-utils/share'

function escapeDoubleQuotes(val: string) {
function escapeDoubleQuotes(val: string): string {
return val.replace(/"/g, '""')
}

/**
* check separator is valid
* @param {string} separator
*/
function checkSeparator(separator: string) {
function checkSeparator(separator: string): void {
if (!separator)
throw new Error('The separator cannot be empty')

Expand Down Expand Up @@ -68,7 +68,7 @@ interface ArrayToCSVOptions<T> {
* ```
* @linkcode https://github.com/GreatAuk/utopia-utils/blob/main/packages/core/src/csv.ts
*/
export function arrayToCSV<T extends (any[] | object)>(arr: T[], options: ArrayToCSVOptions<T> = {}) {
export function arrayToCSV<T extends (any[] | object)>(arr: T[], options: ArrayToCSVOptions<T> = {}): string {
const { headers, separator = ',', getRow, withPrefix } = options

checkSeparator(separator)
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/deepClone.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
function clone<T>(src: T, seen = new Map()) {
function clone<T>(src: T, seen = new Map()): T {
// Immutable things - null, undefined, functions, symbols, etc.
if (!src || typeof src !== 'object')
return src
Expand Down
11 changes: 10 additions & 1 deletion packages/core/src/defineDictionary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,16 @@ type ToValueKey<T> = T extends readonly [infer A, ...infer B]
* @example
* ```ts
// at src/constant.ts
const { get_MUSIC_TYPE_KEYS, get_MUSIC_TYPE_KV, get_MUSIC_TYPE_MAP, get_MUSIC_TYPE_MAP_BY_KEY, get_MUSIC_TYPE_MAP_BY_VALUE, get_MUSIC_TYPE_OPTIONS, get_MUSIC_TYPE_VALUES, get_MUSIC_TYPE_VK } = defineDictionary([
const {
get_MUSIC_TYPE_KEYS,
get_MUSIC_TYPE_KV,
get_MUSIC_TYPE_MAP,
get_MUSIC_TYPE_MAP_BY_KEY,
get_MUSIC_TYPE_MAP_BY_VALUE,
get_MUSIC_TYPE_OPTIONS,
get_MUSIC_TYPE_VALUES,
get_MUSIC_TYPE_VK
} = defineDictionary([
{
key: 'POP',
value: 1,
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/encryptPhone.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@
* @returns The phone number with the middle 4 digits replaced with asterisks.
* @linkcode https://github.com/GreatAuk/utopia-utils/blob/main/packages/core/src/encryptPhone.ts
*/
export function encryptPhone(phone: `${number}`) {
export function encryptPhone(phone: `${number}`): string {
return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}
2 changes: 1 addition & 1 deletion packages/core/src/escapeStringRegexp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@
* @param [string] - The string to escape. Defaults to an empty string.
* @linkcode https://github.com/GreatAuk/utopia-utils/blob/main/packages/core/src/escapeStringRegexp.ts
*/
export const escapeStringRegexp = (string = '') =>
export const escapeStringRegexp = (string = ''): string =>
string.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d')
2 changes: 1 addition & 1 deletion packages/core/src/formatNumberThousand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ interface Options {
* ```
* @linkcode https://github.com/GreatAuk/utopia-utils/blob/main/packages/core/src/formatNumberThousand.ts
*/
export function formatNumberThousand(num: number, options: Options = {}) {
export function formatNumberThousand(num: number, options: Options = {}): string {
if (Number.isNaN(num))
return ''

Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/getFileName.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@
* @returns file name
* @linkcode https://github.com/GreatAuk/utopia-utils/blob/main/packages/core/src/getFileName.ts
*/
export function getFileName(path: string) {
export function getFileName(path: string): string {
return path.replace(/^.*(\\|\/)/, '')
}
2 changes: 1 addition & 1 deletion packages/core/src/getQueryParams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import type { LocationQuery } from './parseQuery'
* ```
* @linkcode https://github.com/GreatAuk/utopia-utils/blob/main/packages/core/src/getQueryParams.ts
*/
export function getQueryParams<T extends LocationQuery>(location: string) {
export function getQueryParams<T extends LocationQuery>(location: string): Partial<T> {
let query: LocationQuery = {}

const searchPos = location.indexOf('?')
Expand Down
5 changes: 3 additions & 2 deletions packages/core/src/objectKeys.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
type ObjectKeysReturn<T> = (keyof T & (string | number | boolean | null | undefined))[]
/**
* strict type Object.keys()
* @param {T} obj - T
* @linkcode https://github.com/GreatAuk/utopia-utils/blob/main/packages/core/src/objectKeys.ts
*/
export function objectKeys<T extends object>(obj: T) {
return Object.keys(obj) as (keyof T & (string | number | boolean | null | undefined))[]
export function objectKeys<T extends object>(obj: T): ObjectKeysReturn<T> {
return Object.keys(obj) as ObjectKeysReturn<T>
}

// const symbol = Symbol('symbol')
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/onWindowFocus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { debounce } from './vendor'
* ```
*
*/
export function onWindowFocus(callback: (...args: any[]) => any) {
export function onWindowFocus(callback: (...args: any[]) => any): () => void {
const listener = debounce(100, callback)

window.addEventListener('focus', listener, false)
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/once.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,6 @@ import { callLimit } from './callLimit'
* ```
* @linkcode https://github.com/GreatAuk/utopia-utils/blob/main/packages/core/src/once.ts
*/
export function once<T extends (...args: any[]) => any>(fn: T) {
export function once<T extends (...args: any[]) => any>(fn: T): (this: ThisParameterType<T>, ...args: Parameters<T>) => ReturnType<T> {
return callLimit(fn, 1)
}
2 changes: 1 addition & 1 deletion packages/core/src/onlyResolvesLast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
* ```
* @linkcode https://github.com/GreatAuk/utopia-utils/blob/main/packages/core/src/onlyResolvesLast.ts
*/
export function onlyResolvesLast<T extends (...args: any) => Promise<any>>(fn: T) {
export function onlyResolvesLast<T extends (...args: any) => Promise<any>>(fn: T): (this: ThisParameterType<T>, ...args: Parameters<T>) => ReturnType<T> {
let time = 0
function wrappedFn(this: ThisParameterType<T>, ...args: Parameters<T>): ReturnType<T> {
const currentTime = time + 1
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/parseQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export function decode(text: string | number): string {
expect(params.sex).toBe(null)
```
*/
export function parseQuery<T extends LocationQuery>(search: string) {
export function parseQuery<T extends LocationQuery>(search: string): T {
const query: LocationQuery = {}
// avoid creating an object with an empty key and empty value
// because of split('&')
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/randomInt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@
* @returns A random integer between min and max.
* @linkcode https://github.com/GreatAuk/utopia-utils/blob/main/packages/core/src/randomInt.ts
*/
export function randomInt(max: number, min = 0) {
export function randomInt(max: number, min = 0): number {
return Math.floor(Math.random() * (max - min + 1) + min)
}
2 changes: 1 addition & 1 deletion packages/core/src/randomString.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* @returns A random string of the length specified.
* @linkcode https://github.com/GreatAuk/utopia-utils/blob/main/packages/core/src/randomString.ts
*/
export const randomString = (length: number, chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') => {
export const randomString = (length: number, chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'): string => {
const maxPos = chars.length
let str = ''
for (let i = 0; i < length; i++)
Expand Down
Empty file removed packages/core/src/utils.ts
Empty file.
2 changes: 1 addition & 1 deletion packages/dom/src/canUseDom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@
* @returns a boolean value indicating whether the DOM (Document Object Model) can be used.
* @linkcode https://github.com/GreatAuk/utopia-utils/blob/main/packages/dom/src/canUseDom.ts
*/
export function canUseDom() {
export function canUseDom(): boolean {
return !!(typeof window !== 'undefined' && window.document && window.document.createElement)
}
2 changes: 1 addition & 1 deletion packages/dom/src/domContains.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
* otherwise.
* @linkcode https://github.com/GreatAuk/utopia-utils/blob/main/packages/dom/src/contains.ts
*/
export function domContains(root: Node | null | undefined, n: Node | null) {
export function domContains(root: Node | null | undefined, n: Node | null): boolean {
if (!root)
return false

Expand Down
16 changes: 8 additions & 8 deletions packages/dom/src/dynamicCSS.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ interface Options {
mark?: string
}

function getMark({ mark }: Options = {}) {
function getMark({ mark }: Options = {}): string {
if (mark)
return mark.startsWith('data-') ? mark : `data-${mark}`

Expand All @@ -48,13 +48,13 @@ function getOrder(prepend?: Prepend): AppendType {
/**
* Find style which inject by rc-util
*/
function findStyles(container: ContainerType) {
function findStyles(container: ContainerType): HTMLStyleElement[] {
return Array.from(
(containerCache.get(container) || container).children,
).filter(node => node.tagName === 'STYLE') as HTMLStyleElement[]
}

export function injectCSS(css: string, option: Options = {}) {
export function injectCSS(css: string, option: Options = {}): HTMLStyleElement | null {
if (!canUseDom())
return null

Expand Down Expand Up @@ -111,15 +111,15 @@ export function injectCSS(css: string, option: Options = {}) {
return styleNode
}

function findExistNode(key: string, option: Options = {}) {
function findExistNode(key: string, option: Options = {}): HTMLStyleElement | undefined {
const container = getContainer(option)

return findStyles(container).find(
node => node.getAttribute(getMark(option)) === key,
)
}

export function removeCSS(key: string, option: Options = {}) {
export function removeCSS(key: string, option: Options = {}): void {
const existNode = findExistNode(key, option)
if (existNode) {
const container = getContainer(option)
Expand All @@ -130,7 +130,7 @@ export function removeCSS(key: string, option: Options = {}) {
/**
* qiankun will inject `appendChild` to insert into other
*/
function syncRealContainer(container: ContainerType, option: Options) {
function syncRealContainer(container: ContainerType, option: Options): void {
const cachedRealContainer = containerCache.get(container)

// Find real container when not cached or cached container removed
Expand All @@ -149,7 +149,7 @@ function syncRealContainer(container: ContainerType, option: Options) {
/**
* manually clear container cache to avoid global cache in unit testes
*/
export function clearContainerCache() {
export function clearContainerCache(): void {
containerCache.clear()
}

Expand All @@ -166,7 +166,7 @@ export function clearContainerCache() {
* updateCSS('body { color: red }', 'my-style')
* ```
* */
export function updateCSS(css: string, key: string, option: Options = {}) {
export function updateCSS(css: string, key: string, option: Options = {}): HTMLStyleElement | undefined {
const container = getContainer(option)

// Sync real parent
Expand Down
2 changes: 1 addition & 1 deletion packages/dom/src/isAndroid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* @returns A boolean value.
* @linkcode https://github.com/GreatAuk/utopia-utils/blob/main/packages/dom/src/isAndroid.ts
*/
export function isAndroid() {
export function isAndroid(): boolean {
if (typeof navigator === 'undefined')
return false
return /android/i.test(navigator.userAgent)
Expand Down
2 changes: 1 addition & 1 deletion packages/dom/src/isIOS.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* @returns A boolean value.
* @linkcode https://github.com/GreatAuk/utopia-utils/blob/main/packages/dom/src/isIOS.ts
*/
export function isIOS() {
export function isIOS(): boolean {
if (typeof navigator === 'undefined')
return false
return /iPad|iPhone|iPod/.test(navigator.userAgent)
Expand Down
2 changes: 1 addition & 1 deletion packages/dom/src/isMobile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* @returns A boolean value.
* @linkcode https://github.com/GreatAuk/utopia-utils/blob/main/packages/dom/src/isMobile.ts
*/
export function isMobile() {
export function isMobile(): boolean {
if (typeof navigator === 'undefined' || typeof window === 'undefined')
return false

Expand Down
2 changes: 1 addition & 1 deletion packages/dom/src/isWeixin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* @returns A boolean value.
* @linkcode https://github.com/GreatAuk/utopia-utils/blob/main/packages/dom/src/isWeixin.ts
*/
export function isWeixin() {
export function isWeixin(): boolean {
const ua = navigator.userAgent.toLowerCase()
return /MicroMessenger/i.test(ua)
}
15 changes: 13 additions & 2 deletions packages/dom/src/loadCSS.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
/**
* Options for {@link loadCSS} function
*/
interface LoadCSSOptions {
/**
* Media query for styles to apply
Expand All @@ -11,6 +14,14 @@ interface LoadCSSOptions {
attrs?: Record<string, string>
}

/**
* return type of {@link loadCSS} function
*/
interface LoadCSSReturn {
unload: () => void
linkTag: HTMLLinkElement
}

/**
* It loads a CSS file into the page
* @param {string} path - the path to the CSS file
Expand All @@ -20,7 +31,7 @@ interface LoadCSSOptions {
* - linkTag: the link tag that was created
* @linkcode https://github.com/GreatAuk/utopia-utils/blob/main/packages/dom/src/loadCSS.ts
*/
export function loadCSS(path: string, options?: LoadCSSOptions) {
export function loadCSS(path: string, options?: LoadCSSOptions): LoadCSSReturn {
const {
attrs = {},
media,
Expand Down Expand Up @@ -48,7 +59,7 @@ export function loadCSS(path: string, options?: LoadCSSOptions) {
}

/** remove the script tag */
function unload(path: string) {
function unload(path: string): void {
const linkEl = document.querySelector(`link[href="${path}"]`)
if (linkEl)
linkEl.remove()
Expand Down
Loading

0 comments on commit 9915cf4

Please sign in to comment.