Skip to content

Constant / compile-time-only functions #26534

Closed
@thargol1

Description

@thargol1

Search Terms

const compiler keyword functions

Suggestion

Allow for functions to be marked as 'const', a function marked as 'const' can be evaluated at compile time.

Allow for functions to be marked as 'compiler', a function marked with compiler can only be evaluated at compile time and is not emitted in the final code.

Functions marked with 'compiler' van only be called with arguments that are constants, or the result
from other 'compiler' functions.

Use Cases

Calculate and generate 'stuff' at compile time instead of runtime.

Examples

const x = concat("a","b");

const function concat(a: string, b: string) : string
{
	return a + b;
}

Compiles to (ES5):

var x = "ab";
function concat(a, b) {
	return a + b;
}

const x = concat("a","b");

compiler function concat(a: string, b: string) : string
{
	return a + b;
}

Compiles to (ES5):

var x = "ab";

const templateFunction = compileHandleBars("<p>{{a}}<p>");

compiler function compileHandleBars(template: string) : Function
{
	// code for compiling handlebars template ommitted.
}

Compiles to:

var templateFunction = function(object) {
	// generated handlebars code ommited.
}

const myVueTemplate = optimizeHtml(`
<div>
	<p>{{a}}</p>
</div>
`);

compiler function optimizeHtml(html: string) : string
{
	// code for optimizing html ommitted.
}

Compiles to:

var myVueTemplate = "<div><p>{{a}}</p></div>";

compiler const PngDataUriPrefix = "data:image/png;base64,";
const myImage = PngDataUriPrefix + getBinaryFileAsBase64("~/logo.png");

compiler function getBinaryFileAsBase64(path: string) : string
{
	// code for reading file from disk and base64-encoding ommitted
}

Compiles to:

var myImage = "data:image/png;base64,0lGODl ... ommitted... hEAAQAM=";

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript / JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. new expression-level syntax)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Out of ScopeThis idea sits outside of the TypeScript language design constraintsSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions