как исправить ошибку в typescript?

Пишу файлы google.strategy и yandex.strategy на typescript, и появилась ошибка когда я написала несколько переменных для создания профиля пользователя:

 const { displayName, emails, photos } = profile

 const user ={
     email: emails[0].value,
     name: displayName,
     picture: photos[0].value
 }

Ошибка именно в строчках emails[0].value и photos[0].value. VS Code говорит, что в них лежат значения undefined. Текст ошибки:

Возможно, "emails" имеет значение undefined.ts(18048)

const emails: {
    value: string;
    verified: boolean;
}[] | undefined

И вот что написано в profile:

export interface Profile extends passport.Profile {
profileUrl: string;
provider: "google";
/**
 * An identifier for the user, unique among all Google accounts and
 * never reused. A Google account can have multiple email addresses at
 * different points in time, but the sub value is never changed. Use sub
 * within your application as the unique-identifier key for the user.
 * Maximum length of 255 case-sensitive ASCII characters.
 *
 * Ex: `"10769150350006150715113082367"`
 */
id: string;
emails?: Array<{ value: string; verified: boolean }>;
_raw: string;
/**
 * ID Token payload, adhering to Google's implementation of the OpenID
 * Connect standard See
 * [documentation](https://developers.google.com/identity/protocols/oauth2/openid-connect#an-id-tokens-payload)
 *
 * An ID token is a JSON object containing a set of name/value pairs. Here's an example, formatted for readability:
 * ```json
 * {
 *   "iss": "https://accounts.google.com",
 *   "azp": "1234987819200.apps.googleusercontent.com",
 *   "aud": "1234987819200.apps.googleusercontent.com",
 *   "sub": "10769150350006150715113082367",
 *   "at_hash": "HK6E_P6Dh8Y93mRNtsDB1Q",
 *   "hd": "example.com",
 *   "email": "[email protected]",
 *   "email_verified": true,
 *   "iat": 1353601026,
 *   "exp": 1353604926,
 *   "nonce": "0394852-3190485-2490358"
 * }
 * ```
 */

Ответы (2 шт):

Автор решения: ksa

как исправить ошибку в typescript?

Например вот так редактор ошибок не дает...

interface Profile {
    profileUrl: string;
    provider: "google";
    id: string;
    emails?: Array<{ value: string; verified: boolean }>;
}
const tmp: Profile = {
    profileUrl: '',
    provider: "google",
    id: '1'
}
test1(tmp)
//
function test1(profile: Profile): void {
    const { emails } = profile

    const user ={
         email: emails ? emails[0].value : null
    }
}
→ Ссылка
Автор решения: Grundy

Так как поле emails объявлено опциональным

emails?: Array<{ value: string; verified: boolean }>;

константа emails имеет тип

const emails: {
    value: string;
    verified: boolean;
}[] | undefined 

То есть, может быть либо массивом, либо undefined.

Поэтому нельзя просто обратиться к элементу, так как может быть ошибка.

Для решения нужно либо воспользоваться оператором ?. при обращении

const user ={
    email: emails?.[0].value,

Либо проверить саму переменную

const user ={
    email: emails ? emails[0].value : 'N/A',
→ Ссылка