有没有一种方法可以强制数组中的所有元素?
仅要求对主要Book类型进行“类型连接”。
我希望有某种方法可以从Book类型通用地使元组类型['id','title']成为注释中建议的方式。或至少检查数组长度...
type Book = {
id: string
title: string
visible: boolean
author: string
}
type BookFields = keyof Book
type BookFieldsExtract<ExtractedFields extends BookFields> = Extract<BookFields, ExtractedFields>
const arr: BookFieldsExtract<'id' | 'title'>[] = ['id'] // how to force error if title not inclided in array?
用例:
type SelectedBookFields = BookFieldsExtract<'id' | 'title'>
type ApiRes = ApiResBook<SelectedBookFields> // {book: {id: string, title: string}}
const bookFields: SelectedBookFields[] = ['id', 'title'] // i just don't want to forget some fields when making request
const response = await fetchAPI<ApiReqBookBody, ApiRes>(
'book',
{ fields: { book: bookFields } }
) // response type is {error: true} | {book: {id: string, title: string}}
答案 0 :(得分:1)
我不知道它是否对您有用,但是我会为此元组创建一些值构造函数,并带有一些重载以指导开发人员。考虑:
function makeArrFromKeys<T, A extends keyof T>(obj: T, key1: A): [A]
function makeArrFromKeys<T, A extends keyof T, B extends keyof Omit<T, A>>(obj: T, key1: A, key2: B): [A, B]
function makeArrFromKeys<T, A extends keyof T, B extends keyof Omit<T, A>, C extends keyof Omit<T, A | B>>(obj: T, key1: A, key2: B, key3: C): [A,B,C]
function makeArrFromKeys<T, K extends keyof T>(obj: T, ...keys: K[]): K[] {
return keys;
}
const book: Book = {
id: 'i',
title: 't',
visible: true,
author: 'a'
}
const arr = makeArrFromKeys(book, 'id', 'author', 'title')
// arr has type ['id', 'author', 'title']
我们的功能扩展到三个键,但是如果您要遵循重载,则可以更进一步。函数将使元组完全符合您的需要-键是唯一的,如果您提供需要的'id','title',则会得到['id', 'title']
。
我会说这是在我们可能会做的疯狂类型与可维护且安全的代码之间做出折衷的选择。
答案 1 :(得分:0)
经过一番搜索,找到了一种适用于我的用例的方法:
DELETE FROM `myTable`
WHERE `id` NOT IN (
SELECT `recordid`
FROM (
SELECT MIN(`id`) as `recordid`
FROM `myTable`
GROUP BY `title`
) t
)