💡

分割代入時の型エラーの対処方法

に公開

型エラー文: プロパティ user_name は型 { user_name: string; user_account: string | null; avatar_url: string | null; } | undefined に存在しません。

GetProfileの型
(alias) GetProfile(): Promise<{
    user_name: string;
    user_account: string | null;
    avatar_url: string | null;
} | undefined>
import GetProfile
export async function getCurrentProfile() {
const { user_name } = await GetProfile();//型エラーuser_name
  return 
}

型エラーが起こる原因

undefinedの可能性があるため分割代入できないのでエラーが出ている
なのでundefinedチェックをすればいい

export async function getCurrentProfile() { 
const profile = await GetProfile();
if (!profile) {//undefinedチェック
  return null
}
const {user_name}= profile
  return user_name
}

Discussion