Skip to content

Commit

Permalink
feat: improve typescript definition (#28)
Browse files Browse the repository at this point in the history
This commit improves the typescript definition of `hashValue()` by introducing a generic type argument and an explicit return type. This ensures that the inferred return type of the function matches the type of values in the provided `options` array.

Before:
```ts
const options1 = [1, 2, 3];
const options2 = ['a', 'b', 'c'];
const options3 = ['a', 'b', 'c', 1, 2, 3];
const value1 = hashValue('str', options1); // tsc: type of `value1` is `unknown`
const value2 = hashValue('str', options2); // tsc: type of `value2` is `unknown`
const value3 = hashValue('str', options3); // tsc: type of `value3` is `unknown`
```

After:
```ts
const options1 = [1, 2, 3];
const options2 = ['a', 'b', 'c'];
const options3 = ['a', 'b', 'c', 1, 2, 3];
const value1 = hashValue('str', options1); // tsc: type of `value1` is `number`
const value2 = hashValue('str', options2); // tsc: type of `value2` is `string`
const value3 = hashValue('str', options3); // tsc: type of `value3` is `string | number`
```
  • Loading branch information
kylerjensen authored Jun 15, 2021
1 parent 623195f commit 2e33b3a
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* @param source String to hash.
* @param options Collection of options to get value from.
*/
export default function hashValue(source: string, options: unknown[]) {
export default function hashValue<T>(source: string, options: T[]): T {
let hash = 0;

if (source.length === 0 || options.length === 0) {
Expand Down

0 comments on commit 2e33b3a

Please sign in to comment.