Cast type

2 snippets across 2 stacks — SQL, TypeScript

SQLSQL

CAST / Type Conversion

SQL · String Functions
syntax
CAST(expression AS data_type)
expression::data_type  -- PostgreSQL shorthand
example
SELECT
  CAST(price AS INTEGER) AS rounded_price,
  CAST(order_date AS VARCHAR) AS date_string,
  '42'::INTEGER + 8 AS sum_pg  -- PostgreSQL only
FROM products;
output
-- rounded_price | date_string | sum_pg
-- 29             | 2025-03-15  | 50

Note CAST is ANSI standard. PostgreSQL's :: shorthand is shorter but not portable. Be careful casting — CAST('abc' AS INTEGER) will throw an error. Use TRY_CAST in SQL Server for safe conversions.

TSTypeScript

Type Assertions

TS · Type Annotations
syntax
value as Type
<Type>value  // not in JSX files
example
const rawData = JSON.parse(payload) as { userId: string; role: string };

// HTMLElement narrowing
const canvas = document.getElementById("game") as HTMLCanvasElement;
const ctx = canvas.getContext("2d");

// Double assertion for incompatible types (use sparingly)
const weird = ("hello" as unknown) as number;
output
// Assertions override the compiler — they do NOT perform runtime conversion

Note Type assertions are a compile-time escape hatch — no runtime checking or conversion happens. If you assert incorrectly, you get silent bugs. Prefer type guards (typeof, instanceof) when possible. The angle-bracket syntax <Type>value conflicts with JSX — always use 'as Type' in .tsx files.