lodash の get 関数は JavaScript でネストした値にアクセスする際にとても便利です。しかし、TypeScript でこのような関数を使うと型情報が失われてしまいます。
TypeScript4.1 の機能であるTemplate Literal Typesを使うと、getの適切な型付けが可能となります。
これを実装できるでしょうか?
例えば、
type Data = {
foo: {
bar: {
value: 'foobar';
count: 6;
};
included: true;
};
hello: 'world';
};
type A = Get<Data, 'hello'>; // 'world'
type B = Get<Data, 'foo.bar.count'>; // 6
type C = Get<Data, 'foo.bar'>; // { value: 'foobar', count: 6 }
この課題では、配列へのアクセスは必要ありません。
import type { Equal, Expect } from '@type-challenges/utils'
type cases = [
Expect<Equal<Get<Data, 'hello'>, 'world'>>,
Expect<Equal<Get<Data, 'foo.bar.count'>, 6>>,
Expect<Equal<Get<Data, 'foo.bar'>, { value: 'foobar', count: 6 }>>,
Expect<Equal<Get<Data, 'foo.baz'>, false>>,
Expect<Equal<Get<Data, 'no.existed'>, never>>,
]
type Data = {
foo: {
bar: {
value: 'foobar'
count: 6
}
included: true
}
'foo.baz': false
hello: 'world'
}