gpt4 book ai didi

typescript :将 typeof 与泛型结合使用

转载 作者:行者123 更新时间:2023-12-04 12:56:22 25 4
gpt4 key购买 nike

我有以下场景:

// Some library
interface Bar<T> {
something: T
}

export function foo<T>(b: Bar<T>) {}

// In my code
function anotherFoo(param1: ???) {
MyLib.foo(param1);
}
哪里 ???是我的未知 Bar没有导出,所以我凭直觉试过:
type param<T> = Parameters<typeof foo<T>>[0];

function anotherFoo<X>(param1: param<X>) {
MyLib.foo(param1);
}
但是 type定义是非法的。
使用时 type param = Parameters<typeof foo>[0]; typeof似乎推断 unknown ,即 Bar<unknown>应该怎么做 ???是?
编辑:我的实际情况
import { Observable, of } from 'rxjs';
import { useDispatch, useSelector } from 'react-redux';

type Items = string[];
interface AppStore {
items: Items
}

type SelectFn = Parameters<typeof useSelector>[0];

function useSelectorAsStream<T>(selectFn: SelectFn) {
const items = useSelector<AppStore, T>(selectFn);
const obs: Observable<T> = of(items);
return obs;
}

function PartialReactComponent() {
const myItems: Observable<Items> = useSelectorAsStream<Items>(store => store.items);
}

最佳答案

我相信这应该适合你:

import { Observable, of } from 'rxjs';
import { useDispatch, useSelector } from 'react-redux';

type Items = string[];
interface AppStore {
items: Items
}

type SelectFn<T> = (state: AppStore) => T

function useSelectorAsStream<T>(selectFn: SelectFn<T>) {
const items = useSelector<AppStore, T>(selectFn);
const obs: Observable<T> = of(items);
return obs;
}

function PartialReactComponent() {
const myItems = useSelectorAsStream<Items>(store => store.items);
}
Playground
更新
使用 typeof 以确保安全:
import { Observable, of } from 'rxjs';
import { useDispatch, useSelector } from 'react-redux';

type Items = string[];
interface AppStore {
items: Items
}

type SelectFn<T> = (state: AppStore) => T

type Result<T> =
typeof useSelector extends <State, Selected>(cb: SelectFn<T>) => T
? SelectFn<T>
: never


function useSelectorAsStream<T>(selectFn: Result<T>) {
const items = useSelector<AppStore, T>(selectFn);
const obs: Observable<T> = of(items);
return obs;
}

function PartialReactComponent() {
const myItems: Observable<Items> = useSelectorAsStream<Items>(store => store.items);
}

关于 typescript :将 typeof 与泛型结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66562642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com