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

Improved type safety for token names #1987

Open
LaurensRietveld opened this issue Sep 7, 2023 · 1 comment
Open

Improved type safety for token names #1987

LaurensRietveld opened this issue Sep 7, 2023 · 1 comment

Comments

@LaurensRietveld
Copy link

Take this code block:

const Filter = createToken({
  name: "Filter" as const,
  pattern: new RegExp("filter", "i"),
}) 
const functionName = this.CONSUME(Filter);
return { type: functionName.tokenType.name };

Considering the name of the TokenType interface is always string, the return type of this function is {type: string}.

Where the above snippet is simple/small, this creates overhead for larger grammars where better type information is wanted, and adds the burden of specifying more accurate types to the developer.
Ideally, the types are derived automatically, making the returntype of the MWE type: "Filter"

@LaurensRietveld
Copy link
Author

I managed to work around this by overwriting the CONSUME function, and using my own createToken function. See here:

function createToken<N extends string>(config: Omit<ITokenConfig, "name"> & { name: N }) {
  return origCreateToken(config) as Omit<TokenType, "name"> & { name: N };
}
class ... {
  public CONSUME<S extends TokenType>(token:S) {
    return super.CONSUME(token) as Omit<IToken, "tokenType"> & {tokenType: S}
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant