Urara-Blog/node_modules/.pnpm-store/v3/files/4f/be7d9c7fdecfee1dce274806024d8c2119c62e3709ba62547040ea063a6eb2745d4213b50c5235a035cbcaaa7b8b7d43e655d143734b67054f52b48b962e40
2022-08-14 01:14:53 +08:00

114 lines
2.4 KiB
Text

---
description: 'Enforce template literal expressions to be of `string` type.'
---
> 🛑 This file is source code, not the primary documentation location! 🛑
>
> See **https://typescript-eslint.io/rules/restrict-template-expressions** for documentation.
## Rule Details
Examples of code for this rule:
<!--tabs-->
### ❌ Incorrect
```ts
const arg1 = [1, 2];
const msg1 = `arg1 = ${arg1}`;
const arg2 = { name: 'Foo' };
const msg2 = `arg2 = ${arg2 || null}`;
```
### ✅ Correct
```ts
const arg = 'foo';
const msg1 = `arg = ${arg}`;
const msg2 = `arg = ${arg || 'default'}`;
const stringWithKindProp: string & { _kind?: 'MyString' } = 'foo';
const msg3 = `stringWithKindProp = ${stringWithKindProp}`;
```
## Options
The rule accepts an options object with the following properties:
```ts
type Options = {
// if true, also allow number type in template expressions
allowNumber?: boolean;
// if true, also allow boolean type in template expressions
allowBoolean?: boolean;
// if true, also allow any in template expressions
allowAny?: boolean;
// if true, also allow null and undefined in template expressions
allowNullish?: boolean;
// if true, also allow RegExp in template expressions
allowRegExp?: boolean;
};
const defaults = {
allowNumber: true,
allowBoolean: false,
allowAny: false,
allowNullish: false,
allowRegExp: false,
};
```
### `allowNumber`
Examples of additional **correct** code for this rule with `{ allowNumber: true }`:
```ts
const arg = 123;
const msg1 = `arg = ${arg}`;
const msg2 = `arg = ${arg || 'zero'}`;
```
### `allowBoolean`
Examples of additional **correct** code for this rule with `{ allowBoolean: true }`:
```ts
const arg = true;
const msg1 = `arg = ${arg}`;
const msg2 = `arg = ${arg || 'not truthy'}`;
```
### `allowAny`
Examples of additional **correct** code for this rule with `{ allowAny: true }`:
```ts
const user = JSON.parse('{ "name": "foo" }');
const msg1 = `arg = ${user.name}`;
const msg2 = `arg = ${user.name || 'the user with no name'}`;
```
### `allowNullish`
Examples of additional **correct** code for this rule with `{ allowNullish: true }`:
```ts
const arg = condition ? 'ok' : null;
const msg1 = `arg = ${arg}`;
```
### `allowRegExp`
Examples of additional **correct** code for this rule with `{ allowRegExp: true }`:
```ts
const arg = new RegExp('foo');
const msg1 = `arg = ${arg}`;
```
```ts
const arg = /foo/;
const msg1 = `arg = ${arg}`;
```