# Hello World
template
// type HelloWorld = number // 下面Equal的判断为string 现为 number是错误的
type HelloWorld = string
test
import type { Equal, Expect, NotAny } from '@type-challenges/utils'
type cases = [
Expect<NotAny<HelloWorld>>,
Expect<Equal<HelloWorld, string>>,
]
# Pick
template
// 类型约束 extends keyof 遍历
type MyPick<T, K extends keyof T> = {
[P in K]: T[P];
}
function myPick (todo, keys) {
const obj = {}
keys.forEach(key => {
if (key in todo) {
obj[key] = todo[key]
}
});
return obj;
}
// 1. 返回一个对象
// 2. 遍历forEach
// 3. todo[key] 取值
// 4. 看看key 在不在 todo 里面
// function getPrototype <T, K>(obj: T, key: K) {
function getPrototype <T, K extends keyof T>(obj: T, key: K) {
return obj[key]
}
test
import type { Equal, Expect } from '@type-challenges/utils'
type cases = [
Expect<Equal<Expected1, MyPick<Todo, 'title'>>>,
Expect<Equal<Expected2, MyPick<Todo, 'title' | 'completed'>>>,
// @ts-expect-error
MyPick<Todo, 'title' | 'completed' | 'invalid'>,
]
interface Todo {
title: string
description: string
completed: boolean
}
interface Expected1 {
title: string
}
interface Expected2 {
title: string
completed: boolean
}