Skip to content

Instantly share code, notes, and snippets.

@myuon
Last active January 31, 2020 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save myuon/c583a4d94a0267fbf8b316028c9c3a35 to your computer and use it in GitHub Desktop.
Save myuon/c583a4d94a0267fbf8b316028c9c3a35 to your computer and use it in GitHub Desktop.
type D<T> = {
[P in keyof T]?: T[P] extends Array<infer U> ? Array<D<U>> : T[P]
}
type W<V> = {
wrapper: V
}
type A = D<{
hoge: number,
foo: W<{ bar: string }[]>,
}>
/*
Property 'wrapper' is missing in type 'never[]' but required in type 'W<{ bar: string; }[]>'.(2741)
input.ts(6, 5): 'wrapper' is declared here.
input.ts(11, 5): The expected type comes from property 'foo' which is declared here on type 'D<{ hoge: number; foo: W<{ bar: string; }[]>; }>'
*/
const a: A = {
foo: []
}
@hrdtbs
Copy link

hrdtbs commented Jan 31, 2020

type D<T> = {
    [P in keyof T]?: T[P] extends Array<infer U> ? Array<D<U>> : D<T[P]>
}

こうすると

export const a: A = {
    foo: undefined
}
export const b: A = {
    foo: {
        wrapper: undefined
    }
}

ここまでいけます。

それとPartialは配列は考慮しないので

type A = D<{
    hoge: number,
    foo: W<{ bar: string }[]>,
}>

の場合、{ bar: string }[]{bar: string}[]のままなのは正しいです。

type A = D<{
    hoge: number,
    foo: W<{ bar: string }>,
}>

であればAの型は以下のようになるので

type A = {
    hoge?: number | undefined;
    foo?: D<W<{
        bar: string;
    }[]>> | undefined;
}

barもoptionalになります。

@myuon
Copy link
Author

myuon commented Jan 31, 2020

Dつけたら動いた

type D<T> = {
    [P in keyof T]?: T[P] extends Array<infer U> ? Array<D<U>> : D<T[P]>
}

type W<V> = {
    wrapper: V
}

type A = D<{
    hoge: number,
    foo: W<{ bar: string }[]>,
}>

const a: A = {
    foo: {
        wrapper: [{ bar: '' }, {}]
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment