[英]Return accessed property name (key) from object
Is it possible in Javascript/Typescript to write a function that returns the arguments name/key as string? 是否可以在Javascript / Typescript中编写一个将参数名称/键作为字符串返回的函数?
function foo(arg) {...}
let user = new User();
foo(user.userId) // => returns string: "userId"
foo(user.name) // => returns string: "name"
For my purposes it would be also okay if the function could return the whole expression, means: 就我的目的而言,如果函数可以返回整个表达式,那也可以,这意味着:
foo(user.userId) // => returns string: "user.userId"
foo(user.name) // => returns string: "user.name"
One option is not exactly a function, but a wrapper, if that's acceptable - you could use a Proxy
which intercepts property access and returns the key that was attempted to be accessed: 一个选项并不完全是一个函数,而是一个包装器(如果可以接受的话)-您可以使用
Proxy
来拦截属性访问并返回尝试访问的密钥:
function User() {} const userProxy = new Proxy( new User(), { get: (obj, prop) => prop } ); console.log(userProxy.userId) // => returns string: "userId" console.log(userProxy.name) // => returns string: "name"
There is no nameof
operator in typescript (like in C#). 打字稿中没有
nameof
运算符(例如在C#中)。 There is the keyof
type operator which allows you to specify that a string must be a key of a type. 有一个
keyof
type运算符,它允许您指定字符串必须是类型的键。 So we could rewrite your function to: 因此,我们可以将您的函数重写为:
class User {
userId: number;
name: string
}
function foo<T, K extends keyof T>(arg: T, key: K) {
return key
}
let user = new User();
foo(user, "userId") // => returns string: "userId"
foo(user, "name") // => returns string: "name"
foo(user, "namee") // error
Note There is a nameof
implementation for Typescript by fellow SO user David Sherret you can find it here . 注意 SO的同伴David Sherret为Typescript提供了一个
nameof
实现,您可以在这里找到它。 I have not personally tried it but it may be useful. 我没有亲自尝试过,但是可能有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.