【发布时间】:2021-08-29 16:13:32
【问题描述】:
如果提供了正确类型的对象作为参数,我如何检查函数内部?查看我的示例代码
interface replacementMap {
key: string,
value: string
} // ex [{key: '[last]', value: 'Washington'}, {key: '[first]', value: 'George'}]
type templateString = string // ex `[last], [first]`
const replaceStringsInTemplate = (m: Array<replacementMap>, t: templateString): (string | null) => {
// String is easy to check
if (typeof t !== 'string') return
// But how would I do a check like this?
if (typeof m !== 'replacementMap[]') return null
let rtn = t;
m.forEach((v) => {
rtn = rtn.split(v.key).join(m.value)
}
return rtn;
}
在上面的代码中,如何检查参数m实际上是Array<replacementMap>类型?
【问题讨论】:
标签: typescript interface typechecking typeguards