PROG_WAY_BLOG Telegram 343
progway — программирование, IT
Теги для шаблонных строк В JavaScript есть, как по мне, крайне странный синтаксис. Самым очевидным его применением можно считать styled-components и выглядит всё это примерно так: const display = 'flex'; const Button = styled.button` padding: 10px; …
Ещё один пример

Бывает такое, что нужно встроить в строку значение, которое может быть пустым. Обычно пишутся доп. проверки:
const order = {
city: "Москва" // представим, что возможно undefined или null
}

const { city } = order

// могут писать что-то типа такой проверки
city ? `Ваш город: ${city}` : null


Можно решить эту же задачу с помощью функции из поста выше, вот так это будет:
type SubstitutionPrimitive = string | number | boolean | undefined | null;

const isNullOrUndefined = (value: SubstitutionPrimitive): value is undefined | null => {
return value === undefined || value === null;
};

const safePaste = (strings: TemplateStringsArray, ...substitutions: SubstitutionPrimitive[]) => {
let result = strings[0];

for (let index = 0; index < substitutions.length; index++) {
const value = substitutions[index];

if (isNullOrUndefined(value)) return null;

result += value + strings[index + 1];
}

return result;
};


Просто вернем null вместо строки, если какое либо из значений в подстановках null или undefined. Вот так это будет вызываться:
const apple = {
name: 'Яблоко',
};
const orange = {};

safePaste`Товар: "${apple?.name}"`;
// Товар: "Яблоко"

safePaste`Товар: "${orange?.name}"`;
// null


Ну типа костыль. А вроде и нет. Просто ещё один пример посмотреть как это можно применить

@prog_way_blogчат — #javascript #code
🔥14👍64🐳4



tgoop.com/prog_way_blog/343
Create:
Last Update:

Ещё один пример

Бывает такое, что нужно встроить в строку значение, которое может быть пустым. Обычно пишутся доп. проверки:

const order = {
city: "Москва" // представим, что возможно undefined или null
}

const { city } = order

// могут писать что-то типа такой проверки
city ? `Ваш город: ${city}` : null


Можно решить эту же задачу с помощью функции из поста выше, вот так это будет:
type SubstitutionPrimitive = string | number | boolean | undefined | null;

const isNullOrUndefined = (value: SubstitutionPrimitive): value is undefined | null => {
return value === undefined || value === null;
};

const safePaste = (strings: TemplateStringsArray, ...substitutions: SubstitutionPrimitive[]) => {
let result = strings[0];

for (let index = 0; index < substitutions.length; index++) {
const value = substitutions[index];

if (isNullOrUndefined(value)) return null;

result += value + strings[index + 1];
}

return result;
};


Просто вернем null вместо строки, если какое либо из значений в подстановках null или undefined. Вот так это будет вызываться:
const apple = {
name: 'Яблоко',
};
const orange = {};

safePaste`Товар: "${apple?.name}"`;
// Товар: "Яблоко"

safePaste`Товар: "${orange?.name}"`;
// null


Ну типа костыль. А вроде и нет. Просто ещё один пример посмотреть как это можно применить

@prog_way_blogчат — #javascript #code

BY progway — программирование, IT


Share with your friend now:
tgoop.com/prog_way_blog/343

View MORE
Open in Telegram


Telegram News

Date: |

Polls The optimal dimension of the avatar on Telegram is 512px by 512px, and it’s recommended to use PNG format to deliver an unpixelated avatar. A Hong Kong protester with a petrol bomb. File photo: Dylan Hollingsworth/HKFP. More>> Members can post their voice notes of themselves screaming. Interestingly, the group doesn’t allow to post anything else which might lead to an instant ban. As of now, there are more than 330 members in the group.
from us


Telegram progway — программирование, IT
FROM American