Typescript оператор вопросительный знак

TypeScript и вопросительный знак

В данной статье мы рассмотрим использование вопросительного знака в TypeScript.

Опциональные свойства объекта

Вопросительный знак можно использовать в определении интерфейса или типа для обозначения необязательного свойства объекта. Это означает, что свойство может быть определено или нет.

В приведенном выше примере свойство middleName является необязательным, и его можно опустить при создании объекта типа Person .

Опциональная чейнинг

Опциональная чейнинг (Optional Chaining) — это способ обращения к вложенным свойствам объекта без необходимости проверять наличие промежуточных свойств. Если свойство существует, будет возвращено его значение, в противном случае будет возвращено undefined .

const user = < name: 'Иван', address: < city: 'Москва', street: 'Тверская', >, >; const city = user?.address?.city; // 'Москва' const zip = user?.address?.zip; // undefined 

В приведенном выше примере вместо проверки существования объекта address и свойства city , мы используем опциональную чейнинг для безопасного доступа к свойствам объекта.

Опциональный вызов функции

Опциональный вызов функции позволяет вызывать функцию только в том случае, если она определена. Если функция не определена, результатом будет undefined .

const result = someFunction?.(); // Если someFunction определена, будет вызвана, иначе undefined 

В заключение, вопросительный знак в TypeScript предоставляет удобные и безопасные способы работы с опциональными свойствами объектов и вызовом функций.

Читайте также:  Оформление цикла if в питоне

  • Получить ссылку
  • Facebook
  • Twitter
  • Pinterest
  • Электронная почта
  • Другие приложения

Комментарии

Отправить комментарий

Популярные сообщения

Python вывести количество элементов списка

Python: Вывод количества элементов списка В этой статье мы рассмотрим как выводить количество элементов списка с помощью языка программирования Python. Использование функции len() Для определения количества элементов в списке в Python, используйте встроенную функцию len() . my_list = [1, 2, 3, 4, 5] elements_count = len(my_list) print(«Количество элементов в списке:», elements_count) Этот код создает список my_list , а затем использует функцию len() для подсчета элементов в списке. Результат будет выведен на экран. Использование цикла for Если вы хотите подсчитать количество элементов списка без использования функции len() , вы можете использовать цикл for . my_list = [1, 2, 3, 4, 5] elements_count = 0 for _ in my_list: elements_count += 1 print(«Количество элементов в списке:», elements_count) В этом примере мы инициализируем переменную elements_count значением 0, а затем для каждого элемента в списке увел

Как сделать шашки на python

Как сделать шашки на Python Как сделать шашки на Python В этой статье мы рассмотрим, как создать простую игру в шашки на Python с использованием библиотеки Pygame. Подготовка Для начала установите библиотеку Pygame, используя следующую команду: pip install pygame Создание доски import pygame pygame.init() WIDTH, HEIGHT = 800, 800 ROWS, COLS = 8, 8 SQUARE_SIZE = WIDTH // COLS WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) BLUE = (0, 0, 255) def draw_board(win): win.fill(WHITE) for row in range(ROWS): for col in range(row % 2, COLS, 2): pygame.draw.rect(win, BLACK, (row * SQUARE_SIZE, col * SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE)) def main(): win = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption(«Checkers») clock = pygame.time.Clock() run = True while run: clock.tick(60) for event in pygame.event.get(): if event.ty

Python как перевести число в другую систему счисления

Преобразуйте числа как профессионал! Узнайте, как Python может перевести любое число в любую систему счисления. Даже если вы никогда раньше не сталкивались с программированием, эта статья поможет вам стать экспертом в считывании двоичных, восьмеричных и шестнадцатеричных чисел. Не пропустите возможность раскрыть секреты произвольной системы счисления в Python! Python: Перевод числа в другую систему счисления В языке программирования Python преобразование числа в другую систему счисления может быть выполнено с использованием встроенных функций и методов. Преобразование чисел в двоичную систему Python предоставляет встроенную функцию bin() для преобразования числа в двоичную систему. # Пример преобразования числа в двоичную систему num = 18 binary_num = bin(num) print(binary_num) # Вывод: 0b10010 Преобразование чисел в восьмеричную систему Функция oct() в Python преобразует число в восьмеричную систему. # Пример преобразования числа в восьмеричную систему num = 18

Источник

Typescript оператор вопросительный знак

Last updated: Jan 20, 2023
Reading time · 3 min

banner

# The optional chaining ?. operator in TypeScript

The question mark dot (?.) syntax is called optional chaining in TypeScript and is like using dot notation to access a nested property of an object, but instead of causing an error if the reference is nullish, it short-circuits returning undefined .

Copied!
type Person = address?: country?: string; >; name?: first?: string; >; >; const person: Person = address: country: 'Chile', >, >; console.log(person.address?.country); // 👉️ "Chile" console.log(person.name?.first); // 👉️ undefined

We created a type where the address and name properties are optional.

Most commonly you’ll be fetching this data from a database or reading it from a file, where some of the properties might not have a value.

The first console.log statement uses the optional chaining (?.) operator to access the address.country property on the person object.

Copied!
const person: Person = address: country: 'Chile', >, >; console.log(person.address?.country); // 👉️ "Chile"

The address.country property exists on the person object, so its value gets logged to the console.

The second example uses the optional chaining (?.) operator to access the name.first property on the person object.

However, the property doesn’t exist on the object, so the optional chaining (?.) operator returns undefined .

Copied!
const person: Person = address: country: 'Chile', >, >; console.log(person.name?.first); // 👉️ undefined

Whenever we try to access a property with a nullish ( null or undefined ) reference, the optional chaining operator (?.) short-circuits returning undefined instead of throwing an error.

If we didn’t use the optional chaining (?.) operator, we would have gotten an error because we’re trying to access a property on an undefined value.

Copied!
type Person = address?: country?: string; >; name?: first?: string; >; >; const person: Person = address: country: 'Chile', >, >; // ⛔️ ERROR: Cannot read properties of undefined (reading 'first') console.log(person.name.first); // 👉️ undefined

We didn’t use the optional chaining (?.) operator to short-circuit in case the name property was not set, so an error occurred.

# Optional chaining (?.) vs logical AND (&&) operator

You might have used the logical AND (&&) operator to get around this in the past.

Copied!
type Person = address?: country?: string; >; name?: first?: string; >; >; const person: Person = address: country: 'Chile', >, >; console.log(person.name && person.name.first); // 👉️ undefined

We used the logical AND (&&) operator to check if accessing the name property on the person object returns a truthy value.

If it does, we try to access the first property on the name object.

This is a bit different than using optional chaining because it checks if the reference is truthy, whereas the optional chaining (?.) operator checks that the reference is not null or undefined .

# Using optional chaining to access array indexes

The optional chaining operator can also be used to access an array element at a specific index or short-circuit if the reference is null or undefined .

Copied!
type Person = numbers?: low?: number[]; >; >; const person: Person = >; console.log(person.numbers?.low?.[0]); // 👉️ undefined

The low property could be undefined , so trying to access the array element at index 0 on an undefined value would throw an error unless we use the optional chaining (?.) operator to short-circuit if the reference is undefined .

If the property is populated on the object, the optional chaining operator (?.) returns the specified value in the array.

Copied!
type Person = numbers?: low?: number[]; >; >; const person: Person = numbers: low: [1, 2, 3], >, >; console.log(person.numbers?.low?.[0]); // 👉️ 1

# Using the optional chaining operator with function parameters

The optional chaining (?.) operator can also be used to call a function if its value is not equal to null or undefined .

Copied!
function logger(callback?: (msg: string) => void) callback?.('hello'); > logger(console.log); // 👉️ "hello"

Trying to call the callback parameter would cause an error if it isn’t provided, so we used the optional chaining (?.) operator to check if the reference is not null or undefined before calling the function.

If the parameter is not provided, the operator would just short-circuit returning undefined instead of calling the function.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью