Description
Search Terms
intrinsic 4.1
Suggestion
Allow custom intrinsic implementations or expand on the provided intrinsic selection process.
From #40580 (comment) and #40710 it seems the small set of initial "necessary" intrinsics exist because their operations amount to ubiquitous and unambiguous string manipulations, but what will the future generations of intrinsics include, potentially CamelCase
from #40710 ?
Another option is to allow them to be user-defined. A naive example could be to suggest that a single function is the intrinsic and runtime implementation, e.g.
function mockingly<S extends string>(s: S): intrinsic {
return s.split("").map((c, i) => c[i % 2 ? "toUpperCase" : "toLowerCase"]().join(" ")
}
const test: "H e L l O W o R l D" = mockingly("hello world")
I suggest this syntax because you don't have to hunt down how that intrinsic is implemented or linked into the compiler, but either way I wonder how it will be decided which intrinsics are available if it continues to be the plan to not support custom intrinsics #40710 (comment) and since so far this suggestion trespasses into the "no runtime dependencies" non-goal if intrinsic functions are sourced from runtime modules.
Use Cases
Whenever the compiler and runtime can leverage the same implementation, e.g.
function snakeCase<S extends String>(s: S): intrinsic {
return s.replace(/\W+/g, " ").toLowerCase().split(' ').join('_');
}
function snakeKeys<T>(x: T): intrinsic {
if (Array.isArray(x)) {
return x.map(snakeKeys)
}
if (x != null && typeof x === "object") {
return Object.fromEntries(
Object.entries(o).map(([ key, val ]) => [snakeCase(key), snakeKeys(val)])
)
}
return x
}
// statically unknowable, but still works at runtime
const untyped: object = snakeKeys({ /* ... */ } as object)
// statically known
const typed: { foo_bar: { baz_qux: 'etc' } } = snakeKeys({ FooBar: { bazQux: 'etx' } })
Further, since template types are tempting people to write parsers (maybe impractically) e.g. for graphql #40336 (comment) this allows reuse of existing code.
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. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
❗ - This feature would agree with the rest of TypeScript's Design Goals.