microsoft / microsoft/typespec

Suggestion: Enforce declaring method return types

Open
#333 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
Java
Stars
5.9k
Forks
394
Avg merge
1d 23h
Merged PRs (30d)
104

Description

Applicable ESLint rules:

- [@typescript-eslint/explicit-function-return-type](https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/docs/rules/explicit-function-return-type.md) -- applies to all functions
- [@typescript-eslint/explicit-module-boundary-types](https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/docs/rules/explicit-module-boundary-types.md) -- applies to only exported functions

Basically, consider a decorator helper like:

```ts
export function getStatusCodes(program: Program, entity: Type) {
return program.stateMap(statusCodeKey).get(entity);
}
```

The inferred type is `any` because that's what `stateMap` returns, but really we know for this specific case it's `string[] | undefined` (or `string[]` when you have done an isStatusCode() check first.)

This requires consumers to look into our actual implementation code to determine the data types returned from decorator state methods, which is a bit time consuming and annoying. It also means that breaks could easily occur as we're not enforcing a public contract but relying on casting from `any`.

Consider the alternative:

```ts
export function getStatusCodes(program: Program, entity: Type): string[] {
return program.stateMap(statusCodeKey).get(entity) ?? [];
}
```

Now a consumer knows exactly what they're going to get and they never have to worry about the `undefined` case.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.