我有一个为实例分配属性的构造函数:
#!/bin/bash
# Updates all svn externals in a remote repository
# argument 1 is the server
# argument 2 is the path to the externals directory relative to the server root
#
# Note: all externals in the repository must be relative to the server root.
# See `svn help pset`
#
# Example:
# If you have externals in https://example.com/svn/project1/trunk, then:
#
# this-script https://example.com /svn/project1/trunk
#
server=$1
repo=$2
# Get the commited properties
svn checkout $server$repo wc --depth=empty
svn pget svn:externals wc > wc.externals
# Remove empty lines
sed -i '/^$/d' wc.externals
# for each external in existing properties:
while read line; do
# tokenize
IFS='@ ' tokens=( $line )
# extract interesting stuff from the tokens
extrepo=${tokens[0]}
rev=${tokens[1]}
dir=${tokens[2]}
# Query the external repository for the last change
latest=$(svn info $server$extrepo | sed -ne 's/^Last Changed Rev: //p')
# Write a new set of externals based on latest info
echo "$extrepo@$latest $dir" >> wc.newexternals
done <wc.externals
# Get the differences between the new and old externals
details=$(diff -y --suppress-common-lines wc.externals wc.newexternals)
# If differences exist (and the diff was valid)
retval=$?
if [ $retval -eq 1 ]; then
# Set the new properties
svn pset svn:externals -F wc.newexternals wc
# Generate the SVN log
echo "Automatic externals update" > wc.log
echo $details >> wc.log
# Commit the changes
svn ci -F wc.log wc
fi
# Cleanup
rm -rf wc wc.externals wc.newexternals wc.log
然后我可以创建一个这样的实例:
class BaseModel {
constructor (args = {}) {
for (let key in args) {
this[key] = args[key]
}
}
}
class User extends BaseModel {
name: string
}
我现在想用class-transformer代替此基本功能:
let user = new User({name: 'Jon'})
我的代码库在很多地方都使用第一种方法,因此我想在构造函数中实现新方法,这样我就不会破坏旧代码:
let user = plainToClass(User, {name: 'Jon'})
如何获取构造函数中的类类型?我不能使用User,因为这是基本模型,其他类也可能从其扩展。
答案 0 :(得分:1)
我想它是new.target
。 Doc
要获取构造函数,请使用new.target.prototype.constructor
,它的属性为name
-获取类名。
class BaseModel {
typeName: string;
constructor (args = {}) {
this.typeName = new.taget.constructor.name;
}
}
class User extends BaseModel {
}
const user = new User();
const typeName = user.typeName; // this would return 'User'