给定以下类型:
type Add = (x:number, y:number) => number
Run Code Online (Sandbox Code Playgroud)
我可以声明const该类型的 a 并定义函数的其余部分,而无需显式指定类型。Typescript 知道那x是一个数字,而且确实y是一个数字。
const add: Add = (x, y) => x + y;
Run Code Online (Sandbox Code Playgroud)
我更喜欢使用function而不是定义函数const,但是似乎没有办法输入完整的函数声明。看来您被迫单独定义参数和返回类型。有什么方法可以使用Add下面声明中的类型,这样我就不必指定它x是一个数字并且y是一个数字
function add(x, y) {
return x + y;
}
Run Code Online (Sandbox Code Playgroud)
而不被迫做类似的事情
function add(x: Parameters<Add>[0], y: Parameters<Add>[1]): ReturnType<Add> {
return x + y;
}
Run Code Online (Sandbox Code Playgroud) function Foo(): string {}
Run Code Online (Sandbox Code Playgroud)
意味着 aFoo是一个返回 a 的函数string。
interface SFC {
(props: Props): any;
}
const Foo: SFC = p => {};
Run Code Online (Sandbox Code Playgroud)
表示这Foo是一个与签名匹配的匿名函数,SFC并且p类型为Props。
我如何声明function Foo()匹配SFC?语法是什么?
即,我想使用function关键字 (not const)声明一个函数,并且该函数本身的类型为SFC。
这些不起作用:
function Foo: SFC () {}
function Foo() {}: SFC
Run Code Online (Sandbox Code Playgroud) I am using React hooks and trying to read state from within a callback. Every time the callback accesses it, it's back at its default value.
With the following code. The console will keep printing Count is: 0 no matter how many times I click.
function Card(title) {
const [count, setCount] = React.useState(0)
const [callbackSetup, setCallbackSetup] = React.useState(false)
function setupConsoleCallback(callback) {
console.log("Setting up callback")
setInterval(callback, 3000)
}
function clickHandler() {
setCount(count+1);
if (!callbackSetup) {
setupConsoleCallback(() => {console.log(`Count is: ${count}`)})
setCallbackSetup(true) …Run Code Online (Sandbox Code Playgroud)