Неочевидные моменты Typescript

  • Меня зовут Дима
  • Работаю в веб-студии fuse8
  • В вебе с 2017 года

Что общего

  • JSON.parse()
  • response.json()
  • localStorage.someKey
  • sessionStorage.someKey
  • Array.isArray()

Что общего

Всё приводится к any

  • JSON.parse()
  • response.json()
  • localStorage.someKey
  • sessionStorage.someKey
  • Array.isArray()

                        function parse(value: unknown) {

                        }
                    

                        function parse(value: unknown) {
                            if (Array.isArray(value)) {

                            }
                        }
                    

                        function parse(value: unknown) {
                            if (Array.isArray(value)) {
                                value[0].someKey.title
                            }
                        }
                    

                        function parse(value: unknown) {
                            if (Array.isArray(value)) {
                                value[0].someKey.title // any[]
                            }
                        }
                    

Решение:

  • ts-reset
  • Правило noImplicitAny (tsconfig)
  • Правило no-explicit-any (eslint)

Методы includes и indexOf в массивах

Слишком строгие при использовании as const


                        const allowedUserIds = [1, 2, 3] as const
                    

						const allowedUserIds = [1, 2, 3] as const
						const getUserId = () =>
							Math.floor(Math.random() * 10)
                    

						const allowedUserIds = [1, 2, 3] as const
						const getUserId = () =>
							Math.floor(Math.random() * 10)
						const userId = getUserId()
                    

						const allowedUserIds = [1, 2, 3] as const
						const getUserId = () =>
							Math.floor(Math.random() * 10)
						const userId = getUserId()
						allowedUserIds.includes(userId)
                    

Error

Argument of type 'number' is not assignable
to parameter of type '1 | 2 | 3'


						const allowedUserIds = [1, 2, 3] as const
						const getUserId = () =>
							Math.floor(Math.random() * 10)
						const userId = getUserId()
						allowedUserIds.includes(userId)
                    

Решение:

ts-reset

* также поможет для методов has в Set и Map

Возможность возврата неправильного типа данных в функции с перегрузкой


						function calc(x: unknown, y: unknown): string | number {
						
						}
                    

						function calc(x: number, y: number): number
						function calc(x: unknown, y: unknown): string | number {
							if (typeof x === 'number' && typeof y === 'number')
								return x + y
						}
                    

						function calc(x: number, y: number): number
						function calc(x: string, y: string): string
						function calc(x: unknown, y: unknown): string | number {
							if (typeof x === 'number' && typeof y === 'number')
								return x + y

							if (typeof x === 'string' && typeof y === 'string')
								return 1000;
						}
                    

						function calc(x: number, y: number): number
						function calc(x: string, y: string): string
						function calc(x: unknown, y: unknown): string | number {
							if (typeof x === 'number' && typeof y === 'number')
								return x + y

							if (typeof x === 'string' && typeof y === 'string')
								return 1000;
						
							throw new Error('invalid arguments passed')
						}
                    

						function calc(x: number, y: number): number
						function calc(x: string, y: string): string
						function calc(x: unknown, y: unknown): string | number {
							if (typeof x === 'number' && typeof y === 'number')
								return x + y

							if (typeof x === 'string' && typeof y === 'string')
								return 1000;
						
							throw new Error('invalid arguments passed')
						}
                    

const sumNumber = calc(5, 5) 10 const sumString    = calc('10', '10') 1000

Решение:

  • Тесты
  • По возможности не указывать тип
    возвращаемых значений из функций

						const getInfo = (title: string) => {
							const info = {
								title: `Site name — ${title}`,
							}
						
							return info
						}
						
						const aboutPageInfo = getInfo('About');
                    
aboutPageInfo -> { title: string; }

						const getInfo = (title: string) => {
							const info = {
								title: `Site name — ${title}`,
								debugKey: 'u12d'
							}
						
							return info
						}
						
						const aboutPageInfo = getInfo('About');
                    

						const getInfo = (title: string) => {
							const info = {
								title: `Site name — ${title}`,
								debugKey: 'u12d'
							}
						
							return info
						}
						
						const aboutPageInfo = getInfo('About');
                    
aboutPageInfo -> { title: string; debugKey: string }

						type Info = { title: string; }
						const getInfo = (title: string): Info => {
							const info = {
								title: `Site name — ${title}`,
							}
						
							return info
						}
						
						const aboutPageInfo = getInfo('About');
                    

						type Info = { title: string; }
						const getInfo = (title: string): Info => {
							const info = {
								title: `Site name — ${title}`,
							}
						
							return info
						}
						
						const aboutPageInfo = getInfo('About');
                    
aboutPageInfo -> Info -> { title: string; }

						type Info = { title: string; }
						const getInfo = (title: string): Info => {
							const info = {
								title: `Site name — ${title}`,
								debugKey: 'u12d'
							}
						
							return info
						}
						
						const aboutPageInfo = getInfo('About');
                    

						type Info = { title: string; }
						const getInfo = (title: string): Info => {
							const info = {
								title: `Site name — ${title}`,
								debugKey: 'u12d'
							}
						
							return info
						}
						
						const aboutPageInfo = getInfo('About');
                    

						type Info = { title: string; }
						const getInfo = (title: string): Info => {
							const info = {
								title: `Site name — ${title}`,
								debugKey: 'u12d'
							}
						
							return info
						}
						
						const aboutPageInfo = getInfo('About');
                    
aboutPageInfo -> Info -> { title: string; }

В Typescript структурная типизация

Если что-то выглядит как утка, крякает как утка и ведёт себя как утка, то это утка


						type Info = { title: string; }
                    
 
{ title: string; }

						type Info = { title: string; }
                    
{ title: string; debugKey: string; }
{ title: string; }

						type FormatPrice = { sign?: string; value: number; }
                    

						type FormatPrice = { sign?: string; value: number; }
						
						const formatPrice = (params: FormatPrice) => {
						  const { sign = '$', value } = params;
						  return `${sign} ${value}`;
						}
                    

						type FormatPrice = { sign?: string; value: number; }
						
						const formatPrice = (params: FormatPrice) => {
						  const { sign = '$', value } = params;
						  return `${sign} ${value}`;
						}
						
						const params = { sign: 'USD', value: 10 }
                    

						type FormatPrice = { sign?: string; value: number; }
						
						const formatPrice = (params: FormatPrice) => {
						  const { sign = '$', value } = params;
						  return `${sign} ${value}`;
						}
						
						const params = { sign: 'USD', value: 10 }

						formatPrice(params);
                    

						type FormatPrice = { sign?: string; value: number; }
						
						const formatPrice = (params: FormatPrice) => {
						  const { sign = '$', value } = params;
						  return `${sign} ${value}`;
						}
						
						const params = { sign: 'USD', value: 10 }

						formatPrice(params);
                    

"USD 10"


						type FormatPrice = { symbol?: string; value: number; }
						
						const formatPrice = (params: FormatPrice) => {
						  const { symbol = '$', value } = params;
						  return `${symbol} ${value}`;
						}
						
						const params = { sign: 'USD', value: 10 }

						formatPrice(params);
                    

						type FormatPrice = { symbol?: string; value: number; }
						
						const formatPrice = (params: FormatPrice) => {
						  const { symbol = '$', value } = params;
						  return `${symbol} ${value}`;
						}
						
						const params = { sign: 'USD', value: 10 }

						formatPrice(params);
                    

"$ 10"


					const params = { sign: 'USD', value: 10 }
					formatPrice(params);	
				

					formatPrice({ sign: 'USD', value: 10 });
				

Ошибка

Object literal may only specify known properties, and 'sign' does not exist in type 'FormatPrice'


					formatPrice({ sign: 'USD', value: 10 });
				

					const params = { sign: 'USD', value: 10 }
					formatPrice(params);	
				

Ошибка

Object literal may only specify known properties, and 'sign' does not exist in type 'FormatPrice'


					formatPrice({ sign: 'USD', value: 10 });
				

suppressExcessPropertyErrors: true

*typescript 5.5+ deprecated и не работает

Потеря типизации в Object.keys

* также в Object.entries


						const info = { title: 'about', text: 'some' }
				

						const info = { title: 'about', text: 'some' }

						Object.keys(info).forEach((key) => {
							const value = info[key]
						});
				

Ошибка

No index signature with a parameter of type 'string' was found on type '{ title: string; text: string; }'


						const info = { title: 'about', text: 'some' }

						Object.keys(info).forEach((key) => {
							const value = info[key]
						});
				

Решение:


						const info = { title: 'about', text: 'some' }

						type InfoKeys = keyof typeof info

						Object.keys(info).forEach((key) => {
						  const value = info[key as InfoKeys]
						});
				

Поведение enum’ов соответствует номинативной типизации, а не структурной


						enum LogLevel { Debug = 'Debug', Error = 'Error' }
				

						enum LogLevel { Debug = 'Debug', Error = 'Error' }
						
						const log = (logLevel: LogLevel, text: string) => {}
				

						enum LogLevel { Debug = 'Debug', Error = 'Error' }
						
						const log = (logLevel: LogLevel, text: string) => {}
						
						log(LogLevel.Debug, 'some')
				

						enum LogLevel { Debug = 'Debug', Error = 'Error' }
						
						const log = (logLevel: LogLevel, text: string) => {}
						
						log(LogLevel.Debug, 'some')
				

						enum LogLevel { Debug = 'Debug', Error = 'Error' }
						
						const log = (logLevel: LogLevel, text: string) => {}
						
						log('Debug', 'some')
				

Error

Argument of type '"Debug"' is not assignable to parameter of type 'LogLevel'


						enum LogLevel { Debug = 'Debug', Error = 'Error' }
						
						const log = (logLevel: LogLevel, text: string) => {}
						
						log('Debug', 'some')
				

						enum LogLevel { Debug = 'Debug', Error = 'Error' }
						enum LogLevel2 { Debug = 'Debug', Error = 'Error' }
						
						const log = (logLevel: LogLevel, text: string) => {}
						
						log(LogLevel2.Debug, 'some')
				

Error

Argument of type 'LogLevel2.Debug' is not assignable to parameter of type 'LogLevel'


						enum LogLevel { Debug = 'Debug', Error = 'Error' }
						enum LogLevel2 { Debug = 'Debug', Error = 'Error' }
						
						const log = (logLevel: LogLevel, text: string) => {}
						
						log(LogLevel2.Debug, 'some')
				
  • Тип определяется его структурой, а не его именем
  • Типы с одинаковой структурой взаимозаменяемы, независимо от их имен
  • Объекты могут содержать лишние свойства, главное чтобы совпадала структура обязательных полей в типе

ts-reset

https://github.com/total-typescript/ts-reset

Typescript playground

https://www.typescriptlang.org/play/

Мой телеграмм

https://t.me/berdnikovDima

Вопросы?