https://zenn.dev/senri/articles/typescript-study-logs
先日、私が参加している勉強会で、一問一答のTypeScriptで復習する機会がありました。 車輪の再発明ですが、自分の理解を深めるために、自分なりの言葉でまとめました。
interface Window {
id: number
title: number
}
interface Window {
title: string
}
// Subsequent property declarations must have the same type. Property 'title' must be of type 'number', but here has type 'string'
interfaceの拡張
interface Animal {
name: string
}
interface Bear extends Animal {
honey: boolean
}
type Animal = {
name: string
}
type Animal = {
id: number
}
// Duplicate identifier 'Animal'.
どちらかに優劣があるわけではない。
プロパティの上書きをする時に挙動が異なる
interfaceは先述した通り。
typeでプロパティの上書きを使用する時↓
type Animal = {
id: number
name: string
}
type Bear = Animal & {
id: string
hobby: string
}
// この時点ではエラーが出ない
const human : Bear = {
id: 1, // → Type 'number' is not assignable to type 'never'.
name: 'taro',
hobby: 'programming'
}
// 重複しているidはnever型となっている