---
title: "constExpr(): function in Authoring, TypeShade API reference"
description: "constExpr, a function in Authoring. Author a module-level constant from an IR value expression: the form for a constant that is not a plain scalar."
url: https://typeshade.dev/api/constexpr/
language: en
---

# `constExpr()`

Function in Authoring

Author a module-level constant from an IR value expression: the form for a constant that is not a plain scalar.

`import { constExpr } from 'typeshade/core/ir'`

The signature, the description and the examples come from the compiler's own source at commit af54ddad5.

## Syntax

```ts
function constExpr<T extends ShaderType>(
  name: string,
  type: T,
  value: Node,
): ConstExprDecl<T>
```

## Parameters

**`name` `string`**

the emitted constant name, and the name every reference spells.

**`type` `T extends ShaderType`**

the constant’s shader type, emitted as its declared type.

**`value` `Node`**

a constant-foldable literal node holding the value.

## Return value

`ConstExprDecl<T>`

the `ConstDecl` to put in `module({ consts })`, carrying `.node`.

## Description

`value` is any constant-foldable literal node, a `vec4(...)`, an `arrayLit(...)`, a struct constructor. It emits `const <name>: <type> = <value>;` on both WGSL and GLSL ES 3.00, and the CPU oracle, the same module run in double precision on the CPU, evaluates the same expression, so all three agree on the value.

A scalar constant is the other form. [`constDecl`](https://typeshade.dev/api/constdecl/) takes a `{ wgsl, cpu }` pair and writes them into a `ConstDecl`’s `wgslValue` and `cpuValue`: the shader gets the spelling you want in the source, often a truncated one such as `3.14159265`, while the oracle evaluates the full double. `constExpr` has no such split, because a folded literal node carries one value for both.

The declaration carries `.node`, the typed reference to read it through, so the name is written once. Without it a reader is spelled `constRef('SKY', vec4fT)` — a string the type checker never compares against the declaration, and a second copy of the type, so a rename or a retype is silent at every call site until the GPU compiler sees it.

## Examples

### Example

```ts
import { constExpr, arrayLit, arrayT, vec4, vec4fT } from 'typeshade/core/ir'

const SKY = constExpr('SKY', vec4fT, vec4(0.4, 0.6, 0.9, 1))
const PALETTE = constExpr('PALETTE', arrayT(vec4fT, 2), arrayLit(vec4fT, c0, c1))

const bg = fn('bg', {}, () => SKY.node) // no constRef('SKY', vec4fT)
const m = module({ consts: [SKY], funcs: [bg] })
```

## See also

- [`constDecl`](https://typeshade.dev/api/constdecl/)
- [`module`](https://typeshade.dev/api/module/)

## Source

[`src/core/ir/builder.ts`, line 1121](https://github.com/typeshade/typeshade/blob/af54ddad5/src/core/ir/builder.ts#L1121), at commit af54ddad5
