【TypeScript】TypeScript問題集に問題を追加しました

青色
問65
こちらの
type A = {name: string}
type B = {age: number}
AとBのkeynameとageを合わせたname | age
なUnion型を作ってください
type A = {name: string}
type B = {age: number}
type T1 = keyof (A & B)
問66
こちらの
type MyUnionType =
| { foo: 'a', bar: 1 }
| { foo: 'b', bar: 2 }
| { foo: 'c', bar: 3 }
型を type Foos = 'a' | 'b' | 'c' このようになるようにしてください
type MyUnionType =
| { foo: 'a', bar: 1 }
| { foo: 'b', bar: 2 }
| { foo: 'c', bar: 3 }
type FooType = MyUnionType['foo']
// FooType = "a" | "b" | "c"
//or
type PickField<T, K extends string> = T extends Record<K, any> ? T[K] : never;
type FooType2 = PickField<MyUnionType, 'foo'>
// type FooType2 = "a" | "b" | "c"
問67
こちらの
interface Foo {
foo: number;
common: string;
}
interface Bar {
bar: number;
common: string;
}
function foo(arg){
return arg.foo
}
const result = foo({foo: 9});
関数fooは現状 interface Foo
型を受け取り、 現状Foo
が持つfoo
を返すようになっています。(argはanyです)
この関数をfooAndBarと名前をへんこうして、Foo型が渡された場合はarg.fooを、Bar型の場合はarg.barを返すように 実装して、型付けしてください
interface Foo {
foo: number;
common: string;
}
interface Bar {
bar: number;
common: string;
}
function isFoo(arg: any): arg is Foo {
return arg.foo !== undefined;
}
function fooAndBar(arg: Bar | Foo){
if(isFoo(arg)){
return arg.foo
} else {
return arg.bar
}
}
const result = fooAndBar({foo: 9, common: "fa"});
問68
こちらは
interface NumberMap {
[key: string]: number;
}
const map: NumberMap = {
one: 1,
two: 2,
three: 3,
}
// no error, but incorrect, this key does *not* exist
const lol = map.weoiroweiroew;
// Also cannot do this
// 'map' refers to a value, but is being used as a type here.
type MyKeys = keyof map;
現状mapに割り当てられている実際のproperty以外のプロパティを受け入れてしまっています 実際に渡したもpropertyをもつ型のみを受け入れるようにしてください(map.weoiroweiroewをエラーにししてください)
また type MyKeys = keyof map;を期待する結果であるone | two | threeにしてください
interface NumberMap {
[key: string]: number;
}
function careteMap<T extends NumberMap>(v: T){
return v
}
const map = careteMap({
one: 1,
two: 2,
three: 3,
})
const lol = map.weoiroweiroew;
type MyKeys = keyof typeof map;