我有以下函数,它可能会收到一个未知值:
function formatReason(detail: unknown): string {
if (detail
&& detail instanceof Object
&& detail.constructor.name === 'Object'
&& detail.hasOwnProperty('description')
&& typeof detail['description'] === 'number'
) {
const output = detail['description'];
return output;
}
return '';
}
Run Code Online (Sandbox Code Playgroud)
该detail
参数可以是任意值。如果它是一个具有description
字符串类型属性的对象,则该函数应返回该属性值,否则返回空字符串。
首先,你建议使用any
或unknown
用于detail
参数?
其次,无论我做什么, for 的类型output
最终都是any
. 我怎样才能确定它是string
?
我试图在 Go 中定义一个通用函数,它接受具有某些字段的值,例如ID int
. 我尝试了几种方法,但似乎都不起作用。这是我尝试过的一个例子。
package main
import (
"fmt"
)
func Print[T IDer](s T) {
fmt.Print(s.ID)
}
func main() {
Print(Person{3, "Test"})
}
type IDer interface {
~struct{ ID int }
}
type Person struct {
ID int
Name string
}
type Store struct {
ID int
Domain string
}
Run Code Online (Sandbox Code Playgroud)
这是游乐场链接:https ://gotipplay.golang.org/p/2I4RsUCwagF
在上面的示例中,我想保证传递给Print
函数的每个值都有一个属性ID int
,该属性也可以在函数中访问。有什么方法可以在 Go 中实现此目的,而无需在接口中定义方法(例如GetID() int
)?