なにかお手伝いできることがあればご連絡ください。
お問い合わせはこちらから
※Googleフォームが表示されます
@Component({
async asyncData({ $content, params }) {
const posts = await $content("posts/" + params.slug).fetch();
return { posts };
},
})
export default class Index extends Vue {
head() {
return {
title: this.posts.title,
};
}
}
this.posts.title
がnullになる場合があるとのことで以下のエラーが発生しました。
Object is possibly 'null'.
簡単な対処法として、対象のオブジェクトに!
の修飾子を追加します。
export default class Index extends Vue {
head() {
return {
title: this.posts!.title,
};
}
}
nullでないことを保証する。
export default class Index extends Vue {
head() {
return {
title: this.posts ? this.posts.title : "",
};
}
}
tsconfig.json
に”strictNullChecks”:falseを追加する。
{
...
"strictNullChecks":false,
...
}
画像読み込み時にimportエラーが発生。 読み込む画像に対しての型定義がないのが原因。
import sample from '@client/assets/img/sample.png'
対処法としては、XXX.d.ts
ファイルを、プロジェクト配下に作成後、以下を定義する。
declare module '*.png'
以下のように型推論できるような変数はあえて型定義をしなくても良いらしい。
const a:boolean = false
こっちでOK。
const a = false
オブジェクトにブラケットアクセスする場合に発生。
const user = {
sato: {
age: 11,
sex: "male",
},
suzuki: {
age: 11,
sex: "female",
},
};
const name = "sato";
console.log(user[name].age);
TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{sato ... }'.
indexの型が不明でエラーになっているようです。
indexの型を指定することで回避できます。
type User = {
[key: string]: {
age: number
sex: string
}
}
const user: User = {
sato: {
age: 11,
sex: 'male'
},
suzuki: {
age: 11,
sex: 'female'
}
}
const name = 'sato'
console.log(user[name].age)
なにかお手伝いできることがあればご連絡ください。
※Googleフォームが表示されます