or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

error-handling.mdformatters-types.mdindex.mdmessage-formatting.md
tile.json

message-formatting.mddocs/

0

# Message Formatting

1

2

Core message formatting functionality that processes ICU message strings with variable substitution, pluralization, date/time formatting, and number formatting.

3

4

## Capabilities

5

6

### IntlMessageFormat Constructor

7

8

Creates a new message formatter instance with locale and format configuration.

9

10

```typescript { .api }

11

/**

12

* Creates a new IntlMessageFormat instance

13

* @param message - ICU message string or pre-parsed AST

14

* @param locales - Locale(s) for formatting (defaults to system locale)

15

* @param overrideFormats - Custom format configurations

16

* @param opts - Additional options including custom formatters

17

*/

18

constructor(

19

message: string | MessageFormatElement[],

20

locales?: string | string[],

21

overrideFormats?: Partial<Formats>,

22

opts?: Options

23

);

24

```

25

26

**Usage Examples:**

27

28

```typescript

29

import IntlMessageFormat from "intl-messageformat";

30

31

// Basic message

32

const simple = new IntlMessageFormat('Hello {name}!', 'en-US');

33

34

// Multiple locales with fallback

35

const multiLocale = new IntlMessageFormat(

36

'Hello {name}!',

37

['zh-CN', 'en-US']

38

);

39

40

// Custom number formats

41

const customFormat = new IntlMessageFormat(

42

'Price: {amount, number, currency}',

43

'en-US',

44

{

45

number: {

46

currency: { style: 'currency', currency: 'EUR' }

47

}

48

}

49

);

50

51

// Pre-parsed AST (for performance)

52

import { parse } from '@formatjs/icu-messageformat-parser';

53

const ast = parse('Hello {name}!');

54

const fromAst = new IntlMessageFormat(ast, 'en-US');

55

```

56

57

### Format Method

58

59

Formats the message with provided values, returning the final formatted string or mixed array.

60

61

```typescript { .api }

62

/**

63

* Format the message with provided values

64

* @param values - Object mapping placeholder names to values

65

* @returns Formatted string or mixed array for complex messages

66

*/

67

format<T = void>(

68

values?: Record<string, PrimitiveType | T | FormatXMLElementFn<T>>

69

): string | T | (string | T)[];

70

```

71

72

**Usage Examples:**

73

74

```typescript

75

// Simple variable substitution

76

const msg = new IntlMessageFormat('Hello {name}!', 'en-US');

77

msg.format({ name: 'Alice' }); // "Hello Alice!"

78

79

// Number formatting

80

const numMsg = new IntlMessageFormat(

81

'You have {count, number} items',

82

'en-US'

83

);

84

numMsg.format({ count: 1234 }); // "You have 1,234 items"

85

86

// Date formatting

87

const dateMsg = new IntlMessageFormat(

88

'Today is {today, date, long}',

89

'en-US'

90

);

91

dateMsg.format({ today: new Date() }); // "Today is January 15, 2024"

92

93

// Pluralization

94

const pluralMsg = new IntlMessageFormat(

95

'{count, plural, =0 {no items} one {# item} other {# items}}',

96

'en-US'

97

);

98

pluralMsg.format({ count: 0 }); // "no items"

99

pluralMsg.format({ count: 1 }); // "1 item"

100

pluralMsg.format({ count: 5 }); // "5 items"

101

102

// Select messages

103

const selectMsg = new IntlMessageFormat(

104

'{gender, select, male {He} female {She} other {They}} will respond shortly.',

105

'en-US'

106

);

107

selectMsg.format({ gender: 'female' }); // "She will respond shortly."

108

109

// XML/HTML tag formatting

110

const tagMsg = new IntlMessageFormat(

111

'Click <link>here</link> to continue.',

112

'en-US'

113

);

114

const result = tagMsg.format({

115

link: (chunks) => `<a href="/next">${chunks.join('')}</a>`

116

});

117

// Result: ['Click ', '<a href="/next">here</a>', ' to continue.']

118

```

119

120

### Format To Parts Method

121

122

Formats the message and returns structured parts for advanced processing.

123

124

```typescript { .api }

125

/**

126

* Format the message and return structured parts

127

* @param values - Object mapping placeholder names to values

128

* @returns Array of message parts with type information

129

*/

130

formatToParts<T>(

131

values?: Record<string, PrimitiveType | T | FormatXMLElementFn<T>>

132

): MessageFormatPart<T>[];

133

```

134

135

**Usage Examples:**

136

137

```typescript

138

const msg = new IntlMessageFormat('Hello {name}!', 'en-US');

139

const parts = msg.formatToParts({ name: 'Bob' });

140

// [

141

// { type: PART_TYPE.literal, value: 'Hello ' },

142

// { type: PART_TYPE.literal, value: 'Bob' },

143

// { type: PART_TYPE.literal, value: '!' }

144

// ]

145

146

// Complex message with objects

147

const complexMsg = new IntlMessageFormat(

148

'User: <user>{name}</user>',

149

'en-US'

150

);

151

const complexParts = complexMsg.formatToParts({

152

name: 'Alice',

153

user: (chunks) => ({ type: 'user', content: chunks.join('') })

154

});

155

// [

156

// { type: PART_TYPE.literal, value: 'User: ' },

157

// { type: PART_TYPE.object, value: { type: 'user', content: 'Alice' } }

158

// ]

159

```

160

161

### Resolved Options Method

162

163

Returns the resolved locale and other options used by the formatter.

164

165

```typescript { .api }

166

/**

167

* Get resolved options for this formatter

168

* @returns Object containing resolved locale

169

*/

170

resolvedOptions(): {

171

locale: string;

172

};

173

```

174

175

**Usage Examples:**

176

177

```typescript

178

const msg = new IntlMessageFormat('Hello!', ['zh-CN', 'en-US']);

179

const options = msg.resolvedOptions();

180

console.log(options.locale); // "zh-CN" (if supported) or "en-US"

181

182

// Check which locale was actually used

183

const detectedLocale = new IntlMessageFormat('Test', 'en-GB');

184

console.log(detectedLocale.resolvedOptions().locale); // "en-GB" or fallback

185

```

186

187

### Get AST Method

188

189

Returns the parsed Abstract Syntax Tree for the message.

190

191

```typescript { .api }

192

/**

193

* Get the parsed AST for this message

194

* @returns Array of message format elements

195

*/

196

getAst(): MessageFormatElement[];

197

```

198

199

**Usage Examples:**

200

201

```typescript

202

const msg = new IntlMessageFormat('Hello {name}!', 'en-US');

203

const ast = msg.getAst();

204

// Returns parsed AST structure for advanced processing

205

```

206

207

### Static Methods

208

209

#### Default Locale

210

211

Gets the default system locale.

212

213

```typescript { .api }

214

/**

215

* Get the default system locale

216

* @returns Default locale string

217

*/

218

static get defaultLocale(): string;

219

```

220

221

#### Resolve Locale

222

223

Resolves the best matching locale from provided options.

224

225

```typescript { .api }

226

/**

227

* Resolve the best matching locale

228

* @param locales - Locale or array of locales to resolve

229

* @returns Resolved Intl.Locale object or undefined

230

*/

231

static resolveLocale(

232

locales: string | string[]

233

): Intl.Locale | undefined;

234

```

235

236

#### Static Formats

237

238

Default format configurations that can be customized.

239

240

```typescript { .api }

241

/**

242

* Default format configurations for number, date, and time formatting

243

*/

244

static formats: Formats;

245

```

246

247

**Usage Examples:**

248

249

```typescript

250

// Accessing default locale

251

console.log(IntlMessageFormat.defaultLocale); // "en-US" (example)

252

253

// Resolving locales

254

const resolved = IntlMessageFormat.resolveLocale(['es-MX', 'es', 'en']);

255

console.log(resolved?.toString()); // "es" or best match

256

257

// Customizing global formats (affects all new instances)

258

// Note: Better practice is to use custom formats per instance

259

const customFormats = {

260

number: { ...IntlMessageFormat.formats.number, currency: { style: 'currency', currency: 'EUR' } },

261

date: { ...IntlMessageFormat.formats.date, short: { year: '2-digit', month: 'short', day: 'numeric' } },

262

time: IntlMessageFormat.formats.time

263

};

264

265

// Apply custom formats to specific instances

266

const msg = new IntlMessageFormat('Price: {amount, number, currency}', 'en-US', customFormats);

267

```

268

269

## Types

270

271

```typescript { .api }

272

interface Options extends Omit<ParserOptions, 'locale'> {

273

formatters?: Formatters;

274

}

275

276

interface MessageFormatPart<T> {

277

type: PART_TYPE.literal | PART_TYPE.object;

278

value: string | T;

279

}

280

281

enum PART_TYPE {

282

literal = 0,

283

object = 1

284

}

285

286

type PrimitiveType = string | number | boolean | null | undefined | Date;

287

288

type FormatXMLElementFn<T, R = string | T | (string | T)[]> = (

289

parts: Array<string | T>

290

) => R;

291

292

// From @formatjs/icu-messageformat-parser

293

interface MessageFormatElement {

294

// AST element structure (imported from parser)

295

}

296

297

interface ParserOptions {

298

// Parser configuration options (imported from parser)

299

}

300

```