as const

Zamraża literały w wyrażeniu: najwęższe typy i pola tylko do odczytu.

Na tej stronie

Przykład

#
TypeScript
const LEVELS = ['easy', 'medium', 'hard'] as const
type Level = (typeof LEVELS)[number]
// type Level = "easy" | "medium" | "hard"

function isLevel(value: string): value is Level {
  return (LEVELS as readonly string[]).includes(value)
}

console.log(LEVELS.length)
console.log(isLevel('hard'), isLevel('ekspert'))
Wynik
3
true false

Definicja i zastosowanie

#

Asercja as const sprawia, że TypeScript wnioskuje najwęższe możliwe typy: napisy stają się literałami ("dark" zamiast string), tablice krotkami tylko do odczytu, a pola obiektów readonly.

Dzięki temu z jednej stałej możesz wyprowadzić typ unii dozwolonych wartości: const LEVELS = ["easy", "hard"] as const i type Level = typeof LEVELS[number] daje "easy" | "hard".

To popularna alternatywa dla enumów. Wartości istnieją w JavaScripcie jak zwykła tablica czy obiekt, a typy powstają z nich automatycznie.

Składnia

#
Składnia
const stala = wyrazenie as const

Więcej przykładów

#
Obiekt jako zamiennik enuma
TypeScript
const Status = {
  Draft: 'draft',
  Published: 'published'
} as const

type Status = (typeof Status)[keyof typeof Status]
// type Status = "draft" | "published"

const current: Status = Status.Published
console.log(current)
Wynik
published

Dobre praktyki

#
  • Wzór const X = [...] as const i type T = typeof X[number] daje jednocześnie listę wartości do pętli i typ unii.
  • Obiekt z as const to lżejsza alternatywa enuma, która nie generuje dodatkowego kodu.

Powiązane hasła

#

Widzisz błąd albo brakuje przykładu? Napisz do nas.