Open2
TypeScriptでの配列のユニオンエラー
const obj = {
key1: {
values: ['hoge', 'fuga', 'piyo', '']
},
key2: {
values: ['foo', 'bar', 'fizz', 'buzz']
}
} as const
const keys = ['key1', 'key2'] as const
const result = keys.map(key => obj[key].values.filter(v => v !== ''))
This expression is not callable.
Each member of the union type '{ <S extends "" | "hoge" | "fuga" | "piyo">(predicate: (value: "" | "hoge" | "fuga" | "piyo", index: number, array: readonly ("" | "hoge" | "fuga" | "piyo")[]) => value is S, thisArg?: any): S[]; (predicate: (value: "" | ... 2 more ... | "piyo", index: number, array: readonly ("" | ... 2 more ... | "piyo")[]) => unk...' has signatures, but none of those signatures are compatible with each other.
obj[key].values
は配列のユニオンであるため,ユニオンにfilterメソッドは存在せずエラーとなる.
解決策としては少々強引だがユニオンの配列に変換すればいい
const obj = {
key1: {
values: ['hoge', 'fuga', 'piyo', '']
},
key2: {
values: ['foo', 'bar', 'fizz', 'buzz']
}
} as const
const keys = ['key1', 'key2'] as const
const result = keys.map(key => obj[key].values.map(v => v).filter(v => v !== ''))