---
title: "식과 타입, 그리고 그 변환 결과"
description: "TypeScript의 타입 단언과 구조 분해, 전개, 리터럴, 그리고 런타임에 생성할 수 없는 값을 생성 코드 또는 컴파일 진단과 비교합니다."
url: https://typeshade.dev/ko/guide/language/from-typescript/expressions/
language: ko
---

# 식과 타입

타입 주장은 지워집니다. GPU에 대응하는 말이 있는 모양은 남습니다. TypeScript가 실행 시점에 만들 값은 적힌 자리에서 거절합니다.

## 객체, 배열, 튜플

- ### 구조 분해
  객체 패턴은 필드를 읽습니다. 함수 안의 `const`, `let` 배열 패턴은 길이가 고정된 배열이나 같은 타입의 원소로 이루어진 튜플에서 값을 순서대로 복사합니다. 생략한 자리도 인덱스를 차지하며, 중첩 패턴을 지원하고 원본 식은 한 번만 계산합니다. 범위, 원소 타입과 읽기 전용 접근 규칙은 유지됩니다. 나머지 원소, 기본값, 구조 분해 대입, 매개변수, 벡터의 배열 패턴과 런타임 또는 특수화 상수에 따라 길이가 정해지는 배열은 지원하지 않습니다.
  TypeScript
  ```ts
  export function swapped(v: vec2): vec2 {
    const { x, y } = v
    return vec2(y, x)
  }

  export function endpoints(xs: array<f32, 3>): f32 {
    const [first, , last] = xs
    return first + last
  }
  ```
  생성된 WGSL
  ```wgsl
  fn swapped(v: vec2<f32>) -> vec2<f32> {
    let x = v.x;
    let y = v.y;
    return vec2<f32>(y, x);
  }

  fn endpoints(xs: array<f32, 3>) -> f32 {
    let first = xs[0u];
    let last = xs[2u];
    return (first + last);
  }
  ```
  생성된 GLSL ES 3.00
  ```glsl
  vec2 swapped(vec2 v) {
    float x = v.x;
    float y = v.y;
    return vec2(y, x);
  }

  float endpoints(float[3] xs) {
    float first = xs[0u];
    float last = xs[2u];
    return (first + last);
  }
  ```
- ### 객체 스프레드
  구조체의 필드마다 읽기가 하나씩 생기고, 뒤에 적은 필드가 그 위를 덮습니다.
  TypeScript
  ```ts
  export function lifted(p: Point): Point {
    return { ...p, y: 9. }
  }
  ```
  생성된 WGSL
  ```wgsl
  fn lifted(p: Point) -> Point {
    return Point(p.x, 9.0);
  }
  ```
  생성된 GLSL ES 3.00
  ```glsl
  Point lifted(Point p) {
    return Point(p.x, 9.0);
  }
  ```
- ### 배열 리터럴
  문맥에서 원소 타입과 길이가 정해진 배열 초기자입니다. `array<T, N>` 선언이 그 예입니다. 함수 안의 배열 바인딩 패턴은 같은 타입으로 이루어진 리터럴 초기자에서 타입과 길이를 추론할 수도 있습니다. [array-literal-ramp](https://github.com/typeshade/typeshade/blob/af54ddad5/examples/gallery/array-literal-ramp/array-literal-ramp.shade.ts)
  TypeScript
  ```ts
  export function step3(i: i32): f32 {
    const xs: array<f32, 3> = [0.15, 0.5, 0.9]
    return xs[i]
  }
  ```
  생성된 WGSL
  ```wgsl
  fn step3(i: i32) -> f32 {
    var xs: array<f32, 3> = array<f32, 3>(0.15, 0.5, 0.9);
    return xs[i];
  }
  ```
  생성된 GLSL ES 3.00
  ```glsl
  float step3(int i) {
    float[3] xs = float[3](0.15, 0.5, 0.9);
    return xs[i];
  }
  ```
- ### 튜플
  튜플은 타입이 길이를 고정한 배열입니다. 반환 자리에서도 그렇습니다. [tuple-and-brand](https://github.com/typeshade/typeshade/blob/af54ddad5/examples/gallery/tuple-and-brand/tuple-and-brand.shade.ts)
  TypeScript
  ```ts
  export function bounds(x: f32): [f32, f32] {
    return [x - 1., x + 1.]
  }
  ```
  생성된 WGSL
  ```wgsl
  fn bounds(x: f32) -> array<f32, 2> {
    return array<f32, 2>((x - 1.0), (x + 1.0));
  }
  ```
  생성된 GLSL ES 3.00
  ```glsl
  float[2] bounds(float x) {
    return float[2]((x - 1.0), (x + 1.0));
  }
  ```

## 타입 주장

- ### 리터럴 유니온
  문자열 리터럴 유니온은 [키 타입](https://typeshade.dev/ko/guide/language/string-keys-record/)입니다. 그 밖에 멤버가 모두 한 타입을 가리키는 유니온은 그 타입을 가리킵니다.
  TypeScript
  ```ts
  export function isWire(m: 0 | 1 | 2): bool {
    return m === 2
  }
  ```
  생성된 WGSL
  ```wgsl
  fn isWire(m: i32) -> bool {
    return (m == 2);
  }
  ```
  생성된 GLSL ES 3.00
  ```glsl
  bool isWire(int m) {
    return (m == 2);
  }
  ```
- ### 브랜드 타입
  브랜드는 지워지고 매개변수는 `f32`입니다. [tuple-and-brand](https://github.com/typeshade/typeshade/blob/af54ddad5/examples/gallery/tuple-and-brand/tuple-and-brand.shade.ts)
  TypeScript
  ```ts
  type Metres = f32 & { readonly [m]: 'metres' }
  ```
  생성된 WGSL
  ```wgsl
  fn deeper(d: f32) -> f32 {
    return (d * 2.0);
  }
  ```
  생성된 GLSL ES 3.00
  ```glsl
  float deeper(float d) {
    return (d * 2.0);
  }
  ```
- ### 타입 주장
  타입에 대한 주장일 뿐 변환이 아니라서, 피연산자가 생성하는 코드를 그대로 생성합니다.
  TypeScript
  ```ts
  export function claimed(x: f32): f32 {
    const a = x as f32
    const b = (x satisfies f32)!
    const k = 2. as const
    return a + b * k
  }
  ```
  생성된 WGSL
  ```wgsl
  fn claimed(x: f32) -> f32 {
    return (x + (x * 2.0));
  }
  ```
  생성된 GLSL ES 3.00
  ```glsl
  float claimed(float x) {
    return (x + (x * 2.0));
  }
  ```

## 연산자

- ### 거듭제곱 연산자
  두 타깃 모두 `pow`입니다.
  TypeScript
  ```ts
  export function curved(x: f32): f32 {
    return x ** 2.2
  }
  ```
  생성된 WGSL
  ```wgsl
  fn curved(x: f32) -> f32 {
    return pow(x, 2.2);
  }
  ```
  생성된 GLSL ES 3.00
  ```glsl
  float curved(float x) {
    return pow(x, 2.2);
  }
  ```
- ### `bool`에 쓰는 `&&`
  두 타깃이 모두 가진 연산자이며, 한 번에 `bool` 하나를 다룹니다.
  TypeScript
  ```ts
  export function both(a: bool, b: bool): bool {
    return a && b
  }
  ```
  생성된 WGSL
  ```wgsl
  fn both(a: bool, b: bool) -> bool {
    return (a && b);
  }
  ```
  생성된 GLSL ES 3.00
  ```glsl
  bool both(bool a, bool b) {
    return (a && b);
  }
  ```
- ### 마스크에 쓰는 `&&`
  거절
  마스크는 `all`이나 `any`나 `select`로 묶습니다. [bool-select](https://github.com/typeshade/typeshade/blob/af54ddad5/examples/gallery/bool-select/bool-select.shade.ts)
  TypeScript
  ```ts
  export function both(a: vec2b, b: vec2b): bool {
    return a && b
  }
  ```
  컴파일러 진단
  **[TS8003](https://typeshade.dev/ko/reference/errors/ts8003/)** Logical "&&" requires bool operands.
- ### 선택 필드
  `radius?: f32 | null` 필드는 null과 undefined를 허용하며, 생략하면 undefined가 됩니다([규칙 8.8](https://typeshade.dev/ko/reference/rules/8-8/)). 생성자, 메서드, 접근자, private/protected/readonly 필드와 제네릭 클래스도 nullable 값을 지원합니다. 초기화하지 않은 클래스 필드는 null만 허용하면 null, undefined를 허용하면 undefined로 시작합니다. null만 허용하는 지역 변수는 읽기 전에 대입해야 합니다. Static 데이터, 바인딩, 진입점 IO는 선택적 값을 저장할 수 없습니다. [Nullable 값](https://github.com/typeshade/typeshade/blob/af54ddad5/examples/gallery/null-values/null-values.shade.ts)
  TypeScript
  ```ts
  class Disc {
    center: vec2
    radius?: f32
  }
  ```
  생성된 WGSL
  ```wgsl
  fn cover(d: Disc, p: vec2<f32>) -> f32 {
    return (length((p - d.center)) - select(1.0, d.radius.value, d.radius.present));
  }
  ```
  생성된 GLSL ES 3.00
  ```glsl
  float cover(Disc d, vec2 p) {
    return (length((p - d.center)) - mix(1.0, d.radius.value, d.radius.present));
  }
  ```

## 문자열, 숫자, 불리언

- ### 문자열 값
  거절
  문자열 리터럴은 [키 타입](https://typeshade.dev/ko/guide/language/string-keys-record/)이 필요한 자리에서 허용됩니다. 값 집합이 열린 `string`은 계속 거부됩니다.
  TypeScript
  ```ts
  export function label(x: f32): f32 {
    const name = `band ${x}`
    return x
  }
  ```
  컴파일러 진단
  **[TS8013](https://typeshade.dev/ko/reference/errors/ts8013/)** Template strings are JS. TypeShade has no string type.
- ### `number`
  타입으로 쓴 `number`는 쓰이는 곳을 보고 추론하며, 어디에서도 정해지지 않으면 `f32`입니다. 너비를 고정하려면 `f32`, `i32`, `u32`를 씁니다.
  TypeScript
  ```ts
  export function twice(x: number): number {
    return x * 2
  }
  ```
  생성된 WGSL
  ```wgsl
  fn twice(x: f32) -> f32 {
    return (x * 2.0);
  }
  ```
  생성된 GLSL ES 3.00
  ```glsl
  float twice(float x) {
    return (x * 2.0);
  }
  ```
- ### `boolean`
  타입으로 쓴 `boolean`은 `bool`입니다.
  TypeScript
  ```ts
  export function on(x: boolean): f32 {
    return x ? 1. : 0.
  }
  ```
  생성된 WGSL
  ```wgsl
  fn on(x: bool) -> f32 {
    return select(0.0, 1.0, x);
  }
  ```
  생성된 GLSL ES 3.00
  ```glsl
  float on(bool x) {
    return mix(0.0, 1.0, x);
  }
  ```
- ### 정수 리터럴
  정수로 적은 수는 그 수를 읽는 자리가 요구하는 타입을 가집니다. `let n = -1`처럼 정수로 적은 값으로 초기화한 타입 표기 없는 `let`은 그 값이 닿는 모든 자리에서 타입을 얻습니다. 타입이 있는 상대 옆의 피연산자, 선언된 함수나 생성자, 메서드의 인자, 인덱스, 결과 타입이 선언된 함수의 `return`, 타입이 있는 값의 대입이 그런 자리입니다. 정수로 적은 수로 초기화한 모듈 변수, 코드가 쓰는 정적 필드, 클래스 필드도 같은 방식으로 읽습니다. 어느 사용처도 정하지 않으면 `f32`입니다. `i32`와 `u32`를 함께 요구하거나 정수를 요구하는 사용처가 실수를 요구하는 사용처 옆에 있으면 [`TS8003`](https://typeshade.dev/ko/reference/errors/ts8003/)이 나며, 타입 표기로 타입을 정합니다. 추론으로만 정수가 된 피연산자끼리의 `/`도 거부되므로([`TS8003`](https://typeshade.dev/ko/reference/errors/ts8003/)), 나눗셈의 의미가 다른 줄에 달려 있지 않습니다. 실수로 적은 초기값은 `f32`로 남고, 적은 수로 만든 `const`는 그것을 읽는 자리마다 타입을 얻으며, 횟수를 세는 `for`의 카운터는 [규칙 7.5](https://typeshade.dev/ko/reference/rules/7-5/)가 주는 타입을 유지합니다.
  TypeScript
  ```ts
  class Hit {
    constructor(public index: i32) {}
    offset(value: i32): i32 { return this.index + value; }
  }
  export function counts(): i32 {
    let n = -1;
    const hit = new Hit(n);
    n = hit.index;
    return hit.offset(n);
  }
  ```
  생성된 WGSL
  ```wgsl
  fn Hit_new_into(_dst: ptr<function, Hit>, index: i32) {
    (*_dst) = Hit(index);
  }

  fn Hit_offset(self_: ptr<function, Hit>, value: i32) -> i32 {
    return ((*self_).index + value);
  }

  fn counts() -> i32 {
    var n: i32 = -1;
    var hit: Hit;
    Hit_new_into(&hit, n);
    n = hit.index;
    return Hit_offset(&hit, n);
  }
  ```
  생성된 GLSL ES 3.00
  ```glsl
  Hit Hit_new(int index) {
    return Hit(index);
  }

  int Hit_offset(Hit self_, int value) {
    return (self_.index + value);
  }

  int counts() {
    int n = -1;
    Hit hit = Hit_new(n);
    n = hit.index;
    return Hit_offset(hit, n);
  }
  ```
- ### 증감 연산자
  값이 한 걸음 옮겨 간 결과를 대입합니다.
  TypeScript
  ```ts
  export function stepped(x: f32): f32 {
    let acc: f32 = x
    acc++
    acc--
    return acc
  }
  ```
  생성된 WGSL
  ```wgsl
  fn stepped(x: f32) -> f32 {
    var acc: f32 = x;
    acc = (acc + 1.0);
    acc = (acc - 1.0);
    return acc;
  }
  ```
  생성된 GLSL ES 3.00
  ```glsl
  float stepped(float x) {
    float acc = x;
    acc = (acc + 1.0);
    acc = (acc - 1.0);
    return acc;
  }
  ```
