将类型动态传递给TypeScript中的函数

ldioqlga  于 2023-04-13  发布在  TypeScript
关注(0)|答案(1)|浏览(143)

我有两个这样的interfaces

interface CatStateProps {
    data: CatState[],
    food: number[]
}

interface DogStateProps {
    data: DogState[],
    food: string[]
}

我在type定义中使用了它

type AnimlState= {
    cat?: CatStateProps ,
    dog?: DogStateProps,
};

用这个type我创建了一个对象

const catsAndDogs: AnimlState = {
    cat: {data: [...], food: [...]}
    dog: {data: [...], food: [...]}
};

现在我正在访问dog

let {dog} = catsAndDogs // dog has the types CatStateProps | DogStateProps
if(dog) {
    let {data} = dog // data has the types CatState[] | DogState[]
    foo(data);
}

但是,只要我将data作为函数参数传递给foo(),它就变成了函数foo()中的any类型。

const foo = (data: ?) => {...}

现在,我如何将data的类型传递给foo()函数,而不是这样做

const foo = (data: CatState[] | DogState[]) => {...}

我想在foo()中动态地传递data的类型,当我改变AnimlState时,我不必向foo()添加另一个类型。

vu8f3i0k

vu8f3i0k1#

如果我对这个问题的理解是正确的,你希望你的函数的参数基于AnimlState
你可以像这样实现它:

const foo = (data: Required<AnimlState>[keyof AnimlState]['data']) => { }
             // ^? (parameter) data: CatState[] | DogState[]

TSPlayground
Required用于从AnimlState[keyof AnimlState]中排除undefined作为可能的值,这也可以通过

(data: NonNullable<AnimlState[keyof AnimlState]>['data']) => {}

相关问题