gpt4 book ai didi

typescript - 在 typescript : Is there a way to initialize an object or array inline (with a certain interface type)?

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

在 typescript 中,我想做这样的事情:

interface SomeType {
name: string
}
useState([]:SomeType[]); // This creates an empty array of SomeType inline & calls a function called useState

甚至
function getArrayOfSomeType():SomeType[] {
return []:SomeType[];
}

其他情况可能涉及相同的概念,但带有 map /字典:
// Maybe there is a better way to declare maps?
interface MapOfSomeTypes {
[key:string]: SomeType
}

function getMapOfTypes():MapOfSomeTypes {
return {} as MapOfSometypes; // or perhaps {}:MapOfSomeTypes
}

这是为了避免必须在之前声明这些然后返回它们或将它们传递给另一个函数,当我只需要它们的空版本时(例如 react-hooks)。

最佳答案

无需明确声明它们 - typescript 会为您推断出来,因此

interface SomeType {
name: string
}
useState([]);
function getArrayOfSomeType():SomeType[] {
return [];
}
interface MapOfSomeTypes {
[key:string]: SomeType
}

function getMapOfTypes():MapOfSomeTypes {
return {};
}

关于typescript - 在 typescript : Is there a way to initialize an object or array inline (with a certain interface type)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58772781/

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