Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[engineering] Use type system to indicate when an index starts at one #45706

Closed
mjbvz opened this issue Mar 13, 2018 · 0 comments
Closed

[engineering] Use type system to indicate when an index starts at one #45706

mjbvz opened this issue Mar 13, 2018 · 0 comments
Assignees

Comments

@mjbvz
Copy link
Collaborator

mjbvz commented Mar 13, 2018

Problem

The VS Code codebase has some indexes that start at one (IRange) and some that start at zero. I am very stupid and will not remember this

Proposal

Use types to annotate which types are one indexed:

export interface IRange {
	/**
	 * Line number on which the range starts (starts at 1).
	 */
	readonly startLineNumber: oneIndexedNumber;

      ...
}

Based on microsoft/TypeScript#364, the type could be something like:

declare const __oneIndexedMarker: unique symbol;
type oneIndexedNumber = number & { [__oneIndexedMarker]: '1' };

The benefit of this approach is that it introduces no runtime overhead. It is not perfect however, as it requires casts and can lose the type annotations:

const a = 1 as oneIndexedNumber;
const b = 1 as oneIndexedNumber;

const c = a + b; // type is number

@mhegazy @andy-ms Is a better way to do this with TS? It would be super useful for large codebases like ours

@mjbvz mjbvz self-assigned this Mar 13, 2018
@mjbvz mjbvz closed this as completed Jul 12, 2018
@vscodebot vscodebot bot locked and limited conversation to collaborators Aug 26, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant