如何编写一个可以将任何类型作为参数并保留参数的类型信息的函数?
const shouldPreserveShapeInfo = (t: any) => t // put any because I want it to work with any shape
const input = {
foo: 'bar',
john:'doe'
}
const result = shouldPreserveShapeInfo(input)
// result is now of type any and lost the shape information of input
您可以使用泛型:
const shouldPreserveShapeInfo = <T>(t: T) => t;
const input = {
foo: 'bar',
john:'doe'
}
const result = shouldPreserveShapeInfo(input)
// result is of type { foo: string, john: string }
游乐场