---
title: "값과 변경, TypeShade 작성 가이드"
description: "셰이더 코드 안에서 중간값을 쓰고, 코드에 필요한 자리에 타입을 붙이고, 그 값을 바꾸고, 상수와 변수를 구분하는 방법을 설명합니다."
url: https://typeshade.dev/ko/guide/internals/values-and-mutation/
language: ko
---

# 값과 변경

After this page you can write an intermediate value, give it a type where the code needs one, mutate it, and tell a constant from a variable.

## Types

A type is written where a declaration needs one: a parameter, a return, a struct field, a resource, an annotated local. The names are WGSL’s, written the way TypeScript writes a type.

```ts
"use typeshade";

export function scale(v: vec2, k: f32): vec2 {
  return v * k;
}
```

[`f32`](https://typeshade.dev/ko/reference/types/f32/) is the float scalar, and the type a number written with a decimal point has. [`u32`](https://typeshade.dev/ko/reference/types/u32/) and [`i32`](https://typeshade.dev/ko/reference/types/i32/) are the integer scalars, [`bool`](https://typeshade.dev/ko/reference/types/bool/) is what every comparison produces, and [`vec2`](https://typeshade.dev/ko/reference/types/vec2/), [`vec3`](https://typeshade.dev/ko/reference/types/vec3/) and [`vec4`](https://typeshade.dev/ko/reference/types/vec4/) are the float vectors. The unsigned vectors are [`vec2u`](https://typeshade.dev/ko/reference/types/vec2u/), [`vec3u`](https://typeshade.dev/ko/reference/types/vec3u/) and [`vec4u`](https://typeshade.dev/ko/reference/types/vec4u/), the signed ones [`vec2i`](https://typeshade.dev/ko/reference/types/vec2i/), [`vec3i`](https://typeshade.dev/ko/reference/types/vec3i/) and [`vec4i`](https://typeshade.dev/ko/reference/types/vec4i/), and a matrix is [`mat4`](https://typeshade.dev/ko/api/mat4/) or any `matCxR`. `array<T, N>` is a fixed length array of another type.

Each vector type has a constructor of the same name that builds a value: `vec3(1., 2., 3.)` and `vec3u(1, 2, 3)`. A number written without a decimal point takes the element kind, so `vec3u(1, 2, 3)` emits `vec3<u32>(1u, 2u, 3u)`.

Handed **one whole vector of the same size**, the constructor converts rather than composes: `vec3(v)` on a `vec3u` is WGSL’s `vec3<f32>(v)`, every component through the scalar conversion, and the CPU oracle computes the same. A float source saturates into an integer target and `i32`/`u32` reinterpret two’s-complement, on every target: GLSL ES 3.00 leaves an out-of-range source undefined, so the GLSL writer spells the conversion through `_f2i` and `_f2u`, which saturate as WGSL does ([Rule 11.12](https://typeshade.dev/ko/reference/rules/11-12/)).

## Plain const bindings

Author every intermediate value as a plain `const`. There is nothing to wrap it in:

```ts
const ab = b - a;
const len2 = dot(ab, ab);
```

A `const` holds its value for the rest of the block, and assigning to one is an error. The emit pass decides for each value whether it becomes an inlined expression, a shared `let` (its common subexpression cache) or a named `let` of its own. That decision is not yours to write down.

The GLSL target adds one hoist of its own. An argument to a struct constructor whose value comes from a function that can `discard` is bound to a local variable immediately before the constructor call. It happens on every GLSL emit, so there is nothing to mark in the source, and the WGSL output is unaffected.

## let and const

`let` declares a variable you mean to change, and `const` a value you do not. The type comes from the initial value, or from an annotation, with or without an initial value.

```ts
const d = length(p) - 1.; // let d = …;   read only
let t = 0.; // var t: f32 = 0.0;
let hits: u32 = 0; // var hits: u32 = 0u;
```

A `const` and a module constant are read-only, and assigning to one is [`TS8005`](https://typeshade.dev/ko/reference/errors/ts8005/) at the line that writes it. Declare with `let` when you mean to mutate. A number, a vector or a matrix parameter is a copy of the value the call passes, so a write to it changes the copy and leaves the caller’s variable alone; an object a function writes is the caller’s ([An object a function writes, and a value it gives back](https://typeshade.dev/ko/guide/internals/values-and-mutation/#an-object-a-function-writes-and-a-value-it-gives-back)).

A variable read before it is assigned on every path is [`TS8075`](https://typeshade.dev/ko/reference/errors/ts8075/), by TypeScript’s own rule. A derivative such as [`fwidth`](https://typeshade.dev/ko/reference/functions/fwidth/) needs a value of its own for a different reason: WGSL requires the call in uniform control flow, so bind it to a `const` outside the branch that reads it.

## Mutation and compound assignment

A write is TypeScript’s own assignment. `x = v` writes a value, and `+=`, `-=`, `*=` and `/=` are the compound updates. `++` and `--` step a numeric scalar.

```ts
let minDist = 1e10;
minDist = min(minDist, d);
winding += 1; // emits `winding += 1`
o.pos = vec4(pos, 0., 1.); // a struct field is a target too
o.pos.x = 2.; // and a component of one
```

The two spellings of an update differ in the emitted text, not in meaning: `acc += x` emits `acc += x` and `acc = acc + x` emits `acc = (acc + x)`.

A swizzle target names exactly one component, as in WGSL: `v.xy = …` is refused, so assign each component, or build the whole vector and assign that. Binding a value to another name copies it, as it does on both GPU targets: after `let w = v; w.x = 100.;`, `v` is unchanged. `docs/use-typeshade-surface.md` §9 has every target and refusal.

## Operators

Arithmetic, comparison, bitwise operations, component access and indexing are TypeScript’s operators, and they mean what WGSL means by them:

| category | written |
| --- | --- |
| arithmetic | `+ - * / %` and unary `-` |
| compound | `+= -= *= /= %=` · `++ --` |
| comparison | `< > <= >= == !=` (and `===`, `!==`) |
| logical | `&& \|\| !` |
| bitwise | `& \| ^ << >> ~` |
| casts | `f32(x) i32(x) u32(x) bool(x) f64(x)` |
| components | `.x .y .z .w` · `.r .g .b .a` · `.xy .rgb .zxy …` |
| index | `xs[i]` |
| ternary | `c ? a : b` |
| power | `a ** b`, which lowers to WGSL’s `pow(a, b)` |

A few operations are builtin functions. `select(f, t, c)` is WGSL’s own, so mind the argument order: the condition is last, and `select(f, t, c)` is `c ? t : f`. `mod(x, y)` is the floor modulo, the one to reach for wherever an operand can be negative, as in domain repetition and angle folds; `%` is WGSL’s truncating remainder and behaves differently on negative operands. [`radians`](https://typeshade.dev/ko/reference/functions/radians/) and [`degrees`](https://typeshade.dev/ko/reference/functions/degrees/) convert angles, so a conversion constant of your own never has to be written or rounded.

```ts
const inside = d < 0. && u >= 0.;
const shade = inside ? 1. : 0.;
const cell = mod(p.x, 2.) - 1.;
const lonRad = radians(lon);
const latDeg = degrees(latRad);
```

## A value that may be absent

A value that may be absent is `T | undefined`, as TypeScript writes it: a local, a parameter of a helper, or a function’s result. The compiler carries the value and a `bool` that says whether the value is there, the same on every target. `return undefined;` is the absent value, and so are a bare `return;` and a path that ends the body without a `return`, as TypeScript reads them; `v === undefined` tests it, and `v ?? d` gives `d` where `v` is absent. Loose `v == null` and `v != null` also test absence and presence, with the same narrowing, in either operand order (change 0098, D4). Use `T | null` to store null, or `T | null | undefined` to distinguish both absent states. Strict tests (`=== null`, `=== undefined`) distinguish them; loose tests exclude both.

```ts
"use typeshade";

function root(x: f32): f32 | undefined {
  if (x < 0.) {
    return undefined;
  }
  return sqrt(x);
}

export function rootOr(x: f32, fallback: f32): f32 {
  const v = root(x);
  if (v === undefined) {
    return fallback;
  }
  return v * 2.; // v is an f32 here, as TypeScript reads it
}

export function rootOrOne(x: f32): f32 {
  return root(x) ?? 1.;
}
```

The compiler follows TypeScript’s narrowing: a test `v !== undefined` in an `if`, a `?:`, an `&&`, an `||`, a `while` or a `for`, an early `return`, and an assignment. A read that nothing narrowed is [`TS8003`](https://typeshade.dev/ko/reference/errors/ts8003/), which names the test and the fallback to write. `o?.f` reads a field of an optional struct and is optional itself. A struct field and an array element may hold an optional value in function scope, and an optional parameter `x?: T` is `T | undefined` in the body, which a call may omit; a binding, a module variable, a module constant and an entry’s parameter or result cannot hold one: [`TS8002`](https://typeshade.dev/ko/reference/errors/ts8002/) names the position and the field. An optional has no host value yet, so an exported helper that takes or returns one cannot be called from host code. `docs/use-typeshade-surface.md` §76 has the lowering, the narrowing forms and every refusal.

`T | null` applies to classes, fields, constructors, methods, accessors, callbacks and generic arguments as well as ordinary functions and locals. The two-state null and undefined types share storage but are distinct types; each can widen to the three-state type. An absent receiver in `box?.value` gives undefined, while a present box preserves a null member. Uninitialized nullable class fields start null; fields admitting undefined start undefined. A local `let x: T | null` must be assigned before it is read. Only `?` fields can be omitted from object literals. See `examples/gallery/null-values/null-values.shade.ts` for all three states.

## Number literals

A number written with a decimal point is an `f32`. A number written without one takes the type its position declares, which is WGSL’s abstract-integer rule:

```ts
x + 1.; // f32 x → x + 1.0
flags & 1; // u32 flags → flags & 1u
mode == 2; // u32 mode → mode == 2u
vec4(pos, 0., 1.); // float components
vec2u(0, 1); // → u32 components
```

The position may be a declared type (`let n: u32 = 16`), the operand beside it, a parameter the call passes it to, a struct field or a vector constructor’s element. In every float position the literal stays an `f32`, so `mix(a, b, 1)` is `mix(a, b, 1.0)`. There is no implicit conversion between types: an `i32` value where a `u32` is declared is an error, and the cast is written. `docs/use-typeshade-surface.md` §13 has every position.

Negative literals take the type the same way. `x * -6.`, `x + -0.25` and `vec3(-1., 0., 1.)` emit the signed literal on both targets, so the sign belongs in the number.

## Module constants

A top-level `const` is a module constant: declared once, emitted as a `const` on both targets, and evaluated by the CPU oracle as well. A vector or an array constant carries its value as an expression every backend emits:

```ts
"use typeshade";

const PI: f32 = 3.14159265;
const SKY = vec4(0.4, 0.6, 0.9, 1.);
const PALETTE = array<vec4, 3>(vec4(1., 0., 0., 1.), vec4(0., 1., 0., 1.), vec4(0., 0., 1., 1.));

export function area(r: f32): f32 {
  return r * r * PI;
}

export function tint(i: i32): vec4 {
  return PALETTE[i] * SKY;
}
```

The value must be constant: a literal, a constant declared earlier in the file, a constructor over those, arithmetic over those, or a math builtin over those (`const K: f32 = sin(1.)`). A constant read in a function is a name the editor resolves, so a renamed or misspelt constant is an error at every use site.

A scalar [`f64`](https://typeshade.dev/ko/reference/types/f64/) constant is also allowed: `const TAU: f64 = 2 * Math.PI` folds to a double for the CPU and a literal pair for the GPU. Its permitted builtin calls fold at compile time too. Written `f32` conversions and `f32` operations retain their rounding boundaries; an earlier `f32` constant supplies its recorded compile-time value rounded to `f32`, which need not be the value of its retained GPU builtin expression. Section 12 of `docs/use-typeshade-surface.md` gives the precision rules and the finite-pair range limit.
