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.

Frequently asked questions

How does SQL handle cast type?
This task is covered in 2 stacks on this page: SQL, TypeScript. The "CAST / Type Conversion" snippet in SQL uses `CAST(expression AS data_type)`.
Which statement does the SQL example use?
The "CAST / Type Conversion" snippet uses `CAST(expression AS data_type)`, from the String Functions section of the SQL cheat sheet.
Which stacks cover "cast type" on this page?
SQL, TypeScript. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "CAST / Type Conversion": 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.