如何正确声明带有指定静态变量的TypeScript函数类型
TypeScript约束函数携带指定静态属性的写法
你原先的Function | { id:string }写法是错误的:联合类型|的语义是“满足其中任意一种类型即可”,既允许传入不带id的普通函数,也允许传入不是函数的普通对象,自然无法达成你的要求。
要实现“必须是函数,同时携带指定静态属性”的约束,需要使用交叉类型&合并两类规则,正确写法如下:
// 1. 先定义符合要求的函数类型:此处示例为无参无返回值的函数,额外带string类型的id静态属性 type FuncWithId = (() => void) & { id: string } // 如果需要兼容任意参数、任意返回值的函数,可以替换为下面的泛用写法 // type AnyFuncWithId = (...args: any[]) => any & { id: string } // 2. 给dispatch参数指定上述类型 function dispatch(func: FuncWithId) { console.log('this should be strictly typed', func.id); // 此处id会被TS自动识别为string类型,类型安全 }
给函数添加静态属性的合规写法
直接给普通函数赋值id属性会触发TS的类型报错,推荐两种合规写法:
方法1:用Object.assign创建(推荐,无需额外类型断言,TS可自动推导)
const doThing = Object.assign( () => { console.log('thing done!') }, { id: 'myThingId' } ) dispatch(doThing) // 类型校验通过
方法2:先声明类型再赋值
const doThing = (() => { console.log('thing done!') }) as FuncWithId doThing.id = 'myThingId' // 不会触发类型报错 dispatch(doThing) // 类型校验通过
如果传入不带id属性的普通函数给dispatch,TS会直接抛出类型错误,满足强约束的要求。
内容的提问来源于stack exchange,提问作者tpee
相关产品推荐
相关产品推荐

