[英]Use generics in typescript interface and assign to arrow function
[Edited] I have a quick question on typescript generics, what I am trying to achieve is writing a generic function to insert an array of items of some kind into a firebase database. [已编辑] 我有一个关于 typescript 泛型的快速问题,我想要实现的是编写一个泛型函数以将某种类型的项目数组插入到 firebase 数据库中。 I don't know in advance the array I will receive, so I wrote this function and it works: if I define an arrow function using the generic type I have no errors:
我事先不知道我将收到的数组,所以我写了这个函数并且它有效:如果我使用泛型类型定义一个箭头函数,我没有错误:
export const seedInitialDatas = async <T>(
userUid: string,
collectionName: string,
itemsToSeed: T[]
): Promise<void> => {
itemsToSeed.forEach(async (itemToSeed) => {
await firestore
.collection("users")
.doc(userUid)
.collection(collectionName)
.add(itemToSeed);
});
};
now, instead of having the types defined directly in the function I would like to have a type of an interface to define it:现在,不是直接在函数中定义类型,我希望有一个接口类型来定义它:
type SeedInitialData<T> = (userUid: string, collectionName: string, itemsToSeed: T[]) =>Promise<void>;
export const seedInitialDatas: SeedInitialData = async (
userUid,
collectionName,
itemsToSeed
) => {
itemsToSeed.forEach(async (itemToSeed) => {
await firestore
.collection("users")
.doc(userUid)
.collection(collectionName)
.add(itemToSeed);
});
};
if I do this I receive an error: Generic type 'SeedInitialData' require 1 argument of type如果我这样做,我会收到一个错误:通用类型“SeedInitialData”需要 1 个类型的参数
I'm not 100% sure what you're trying to do but making your function into a type or interface is pretty easy:我不是 100% 确定您要做什么,但是将您的函数变成类型或接口非常简单:
type s<Items> = (userUid: string, collectionName: string, itemsToSeed: Items[]) => void;
export const seedInitialDatas: s<string> = async (
userUid,
collectionName,
itemsToSeed
): Promise<void> => { };
or as interface:或作为接口:
interface s<Items> {
(userUid: string, collectionName: string, itemsToSeed: Items[]): void
};
export const seedInitialDatas: s<string> = async (
userUid,
collectionName,
itemsToSeed
): Promise<void> => { };
Although I'd suggest you using the type as normally interfaces are used for objects尽管我建议您使用该类型,因为通常接口用于对象
I just resolved, I was assinging type T to the type definition instead of the function:我刚刚解决了,我将类型 T 分配给类型定义而不是函数:
type SeedInitialData = <T>(
userUid: string,
collectionName: string,
itemsToSeed: T[]
) => Promise<void>;
export const seedInitialDatas: SeedInitialData = async (
userUid,
collectionName,
itemsToSeed
) => {
itemsToSeed.forEach(async (itemToSeed) => {
await firestore
.collection("users")
.doc(userUid)
.collection(collectionName)
.add(itemToSeed);
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.